Counting characters in a string

Hi, how do I count characters in a string, for example: "MMFRRRRMFMFMRRFFFMMMM"
How could I count the R's but I can only chose a consecutive sequence, so only the first 4 RRRR for example.
Last edited on
Declare your string
string mystring="MMFRRRRMFMFMRRFFFMMMM";

Add a counter
int count=0;

Now you need a for loop
for (int i =0; i<mystring.size();i++)

1
2
3
4
	if (mystring[i]=='R') // if I find a R
	     {count++;} // Add one to count
	else if (count > 0) // check if R has been found, count will be larger than 0
	     {break;}	     // if count is larger than 0 break 
Ok, but what if for example I wanted to find the MMMM all the way at the end, this is the problem im doing http://coj.uci.cu/24h/problem.xhtml?pid=3268 , the string is going to be input by the user and if the size of consecutive R, F, and M are equal then you need to output R, the preference is R > M > F (I know that to do this I will need to do an if r is greater than m output r else...) my question is how to find the consecutive letters that are in the end of the string.

Thanks
In this case you have to adapt SamuelAdams' algorithm slightly:

First of all, you need to store your best-so-far sequence data. You will need an int and a char. I suggest to unite those into struct, buy it is not strictly nessesary.

Then you need to store data for current match. Aside from count you will need cyrrent type too, so add anither char (or just another instance of struct if you went that way).

First of all, set size of best-so-far sequence to 0. Then iterate over your string. While you see consequitive instances of single letter, just increase counter. As soon you found different letter, you will need to check if current sequence is better than best-so-far sequence (compare lengths, compare types if equal) and reassign if nessesary.

Then set type to encountered letter, reset counter to one and continue iterating.
Topic archived. No new replies allowed.