### How to sum repeated consecutive characters in a string?

Hi all, im new to C++ programming. Im really confused with the logic behind this question.

The problem is for an inputted string for instance: "YYNNYYYNYNYY"
i need to calculate the total 'Y's in the string, but for every repeated 'Y' add them consecutively.

so its will become --> 1 + 2 + 0 + 0 + 1 + 2 + 3 + 0 + 1 + 2 = 13

im sorry if the explanation is bad.

how would you format it? i was thinking maybe use s.find() to find the position of Y and then test if the next character in the string is also Y. then add 1 to it but then im really confused in how to link everything together.

or do i have to go through the string one by one by using getchar().

im not sure if you would use arrays, but i havent learnt that yet so thats not allows to be used :/
> or do i have to go through the string one by one

Yes.

> by using getchar().

No. Use either a range based for loop or (archaic compiler) iterate using the [] operator.

 ``12345678910111213141516171819202122`` ``````#include #include int main() { const std::string str = "YYNNYYYNYNYY" ; int total = 0 ; int increment = 0 ; for( char c : str ) // for each character in the string { if( c == 'Y' ) // if it is a 'Y' total += ++increment ; // add one plus the previous increment else // it is not a 'Y' increment = 0 ; // reset increment } std::cout << total << '\n' ; }``````
Thank You Soooo much JLBorgues !!

i tried something else making use of position ... but it doesnt work...

i was just wondering do you think it is feasible .. if not i'll just abandon it >_<

Last edited on
> i was just wondering do you think it is feasible

Of course, it is feasible.

a. The first increment has to be by one (not by the position)
b. `std::string::find()` finds the next occurrence; so you need to look ahead (not behind).
b. The look ahead has to be in a loop; the character may repeat many times.

 ``123456789101112131415161718`` ``````#include #include int main() { const std::string str = "YYNNYNNYYY" ; const char Y = 'Y' ; int total = 0 ; for( auto pos = str.find(Y) ; pos != std::string::npos ; pos = str.find( Y, pos ) ) { for( int increment = 1 ; pos < str.size() && str[pos] == 'Y' ; ++pos, ++increment ) total += increment ; } std::cout << total << '\n' ; }``````
Topic archived. No new replies allowed.