Created
March 5, 2013 04:35
-
-
Save Battleroid/5088039 to your computer and use it in GitHub Desktop.
Count and list occurrences of alphabet letters using a cstring.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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