Counting occurences of letters in a string

William Hemsworth 0 Tallied Votes 788 Views Share

Snippet to show how to count the number of occurences of letters in a string.

#include <iostream>
using namespace std;

// Function to increment the letter count in the counters array
char add_letter( char letter, int counters[] ) {
  // Only deal with lower case letters
  char lower_case_letter = tolower(letter);

  // Check if character is a letter
  if ( lower_case_letter >= 'a' && lower_case_letter <= 'z' ) {
    ++counters[ lower_case_letter - 'a' ];
  }

  return letter;
}

int main() {
  // One integer for each  letter
  int counters[26] = { 0 };

  // Counting the number of occurences of each letter in this sentence
  char *sentence = "the quick brown fox jumps over the lazy dog";

  // Pass each character to the add_letter
  // function until null-terminator is reached
  while ( add_letter(*sentence++, counters) );

  // Display results
  for (int i = 0; i < 26; ++i) {
    if ( counters[i] ) {
      cout << char(i + 'a') << ": " << counters[i] << '\n';
    }
  }

  cin.ignore();
}

Dani AI

Generated

Good minimal example from and nice followups from and . The original C-style snippet demonstrates the idea clearly, but a few safety and portability points are worth adding so the same logic remains correct in real programs.

A safer, idiomatic C++ variant (keeps ASCII a..z counting but avoids UB and deprecated conversions):

#include <iostream>
#include <array>
#include <string>
#include <cctype>

int main() {
  std::string s = "the quick brown fox jumps over the lazy dog";
  std::array<std::size_t, 26> cnt = {};

  for (char ch : s) {
    unsigned char uc = static_cast<unsigned char>(ch);     // avoid passing negative vals
    int lower = std::tolower(uc);                          // returns int
    if (lower >= 'a' && lower <= 'z') ++cnt[lower - 'a'];
  }

  for (std::size_t i = 0; i < cnt.size(); ++i)
    if (cnt[i]) std::cout << char('a' + i) << ": " << cnt[i] << '\n';
}

Notes and troubleshooting tips:

  • Casting to unsigned char before calling std::tolower or std::isalpha avoids undefined behavior on platforms where plain char is signed. These functions expect either EOF or a value representable as unsigned char.
  • Prefer std::string (or const char*) over assigning a string literal to char*. Also remove interactive cin.ignore() from production main.
  • std::isalpha and std::tolower are locale aware; for a strict ASCII-only count the explicit lower >= 'a' && lower <= 'z' check is clearer and stable.
  • For non-ASCII text (UTF-8, accented letters, other scripts) this approach is insufficient. Normalize and decode to Unicode code points and use a Unicode-aware library (ICU or equivalent) to test the "Letter" property and to casefold reliably.

These notes expand on 's isalpha point and keep the core idea from while avoiding common pitfalls.

tux4life 2,072 Postaholic

I've also written such a snippet like this (I haven't posted it though :P)
Nice and well commented :) ...

William Hemsworth 1,339 Posting Virtuoso

Thank you :]

Sky Diploma 571 Practically a Posting Shark

Instead of checking whether the character is a alphabet. wouldn't isalpha do the trick ?

William Hemsworth 1,339 Posting Virtuoso

Well, you could use the isalpha function, but i'm also using the character as an index for an array, so it's just as simple to do it this way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.