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 :/
#include <string>
#include <iostream>
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' ;
}
> 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <string>
#include <iostream>
int main()
{
const std::string str = "YYNNYNNYYY" ;
constchar 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' ;
}