470,616 Members | 2,387 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,616 developers. It's quick & easy.

Extracting char from string

Need to prompt user for text, count occurrence of each alphabetic character, then sort and print in descending order. I'm using two parallel arrays, one for characters, one for occurrence of each, I know how to sort with a for loop. Don't know how to extract from string.

Use something like
while (cin >> s)

Any suggestions?

Program needs to read text until terminated by pressing <enter><ctrl+d>. This is all in a Unix environment, code is C++, if it matters.
Sep 18 '08 #1
4 3981
469 Expert 256MB
You can use the indexing operator, []. myString[i] will give you the character in myString at position i; is this what you're looking for?
For example:
Expand|Select|Wrap|Line Numbers
  1. string myString = "byeworld";
  2. cout << myString[0] << endl; // Prints out b.
  3. cout << myString[1] << endl; // Prints out y.
Or do you already know this and are trying to do something else?
Sep 18 '08 #2
1,275 Expert 1GB
You can get the C string from the string using .c_str() and then work on it as a normal C string.

Sep 18 '08 #3
3,652 Expert 2GB
Are you allowed to use a map? This sort of task would work very well for a map.

Alternatively, you could find a way to use only one array to maintain the count of each letter. You'd have to use the array indexes to indicate which letter you had, though.
Sep 18 '08 #4
9,208 Expert Mod 8TB
Don't know how to extract from string.
You don't need to do this.

I asume your array of counts has been initialized to 0.

All you have to do this look at each character of the string and add 1 to the correct count.
Sep 18 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

7 posts views Thread by cpp_weenie | last post: by
2 posts views Thread by Aleander | last post: by
2 posts views Thread by deanfamily11 | last post: by
6 posts views Thread by Kifah Abbad | last post: by
1 post views Thread by andy.lee23 | last post: by
4 posts views Thread by dor | last post: by
16 posts views Thread by Preben Randhol | last post: by
2 posts views Thread by Pilcrow | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.