I'm trying to find a way to display all the characters in a string and the number of times they occur.
This is what I have so far:
//Any unused includes are part of the default code
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string st = "";
cout << "Input a sentence: " << endl;
getline(cin, st);
int index = 0;
int index2 = 0;
int counters[26] = {0};
for(int i = 0; i < st.length(); i++)
{
int counter = 0;
index = st.find(st[i],0);
for(int j = 0; j < st.length(); j++)
{
index2 = st.find(st[j]);
if(index == index2)
{
counter++;
}
}
cout << st[i] << ": " << counter << endl;
}
//cout << st[i] <<": " << counters[st[i] - 'a'] << endl;
return 0;
}
and I return this:
Input a sentence:
hello
h: 1
e: 1
l: 2
l: 2
o: 1
so I kind of have something but I can't figure out how to make the letters not repeat more than once. I know that I need to store them in an array but it's out of my ken.