So I am writing a code where i want to print out the amount of letters in a string and print it out once but have minor problems of reading the previous letter. For example if the user enters " hello there class" it should print out to the user
There are 2 "h"
there are 3 "e"
there are 3 "l"....etc
can someone help me out and show me the way i am pretty sure I use a pointer but is it possible not to use a pointer because i get really confused when using them. Thank you in advanced.
favor [] over .at(); its faster, only use .at() if you may go out of bounds (it checks).
there are 2 fairly straightforward ways to do this.
1) sort a copy of the string, and iterate, it will be in a form abbbcddde etc where you can just count the same ones until it changes to something else. the length will be the same as it was.
2) you can make a container (vector, or even a c-array) of integers set to zero and increment each one by using the letter's numeric value (this is not useful in unicode, but its fine for ascii):
char counter[256] = {0};
for(...)
counter[string[i]]++;
cout << blah bah there are << counter['e'] << e's in that.
you don't need any pointers at all for either approach.
don't forget that 'e' and 'E' are not the same, if you care.
yah that makes sense in a way i kinda understand so if i create a empty string and add the element once to that string i can compare it if i understand it right sort of like this in a way but of course there are some syntex errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//for loop begin
copy[i] = sentence[i];
if(copy[i] != copy[i + 1]){
cout << "the letter is " << copy[i] << "has already been read" << endl;
}
else{
if(copy[i] == sentence[i]){
cout << "The letter " << copy[i] << "has not been read" << endl;
continue;
}
}
//for loop end
I have no idea what you are doing there.
if(copy[i] == sentence[i]){ //this is always true, you never modified them and its a copy of it.
if you are trying approach 1) you forgot the SORT part?
assuming a string has been sorted, then, its more like
tmp = sorted[0];
count = 1;
for(all the letters)
{
if(sorted[i] == sorted[i+1]_
count ++;
else
{
cout "words" there are count number of sorted[i]'s found
count = 1; //after printing it! not before :P
//here it resets the counter and next iteration is checking the i+1 that was different against i+2 .. new letter, new count... etc..
}
}
#include <iostream>
#include <cctype>
usingnamespace std;
int main()
{
int character_count[26]{0};
string sentence = " ";
cout << "enter sentence to see how many letter of each you will get: ";
getline(cin,sentence);
cout << "here is the senctence you entered\n" << sentence << endl;
char ch;
for(int i = 0; i < sentence.length(); i++)
{
ch = toupper(sentence[i]);
if( isalpha(ch) )
{
character_count[ch - 'A']++;
}
}
for (int i = 0; i < 26; i++)
{
cout
<< "there are " << character_count[i] << " letter of "
<< (char)('A' + i) << endl;
}
return 0;
}