Skip to content

Instantly share code, notes, and snippets.

@Battleroid
Created March 5, 2013 04:35
Show Gist options
  • Save Battleroid/5088039 to your computer and use it in GitHub Desktop.
Save Battleroid/5088039 to your computer and use it in GitHub Desktop.
Count and list occurrences of alphabet letters using a cstring.
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
// can't remember, do I need to include cstring?
void count (string input) {
// Setup arrays
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
int occurrences[26];
// Initialize array with zeros
for (int i = 0; i < 26; i++) {
occurrences[i] = 0;
}
// Count characters
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < 26; j++) {
// use tolower as our cstring is in lowercase
if (tolower(input[i]) == alphabet[j]) {
occurrences[j] += 1;
}
}
}
// Output
for (int i = 0; i < 26; i++) {
printf("%c: %d times\n", alphabet[i], occurrences[i]);
}
}
int main () {
string input;
// Get entire line to avoid breakage
cout << "Enter a string: ";
getline(cin, input);
// Call function
count(input);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment