Counting occurences of letters in a string

William Hemsworth 0 Tallied Votes 703 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();
}
mvmalderen 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.