Originally Posted by
annaz
Thank you so much! That was a very quick response.
I might have not explained the problem correctly. For input: "This is a random string" the output should be: "This IS a RANDOM string."
I'm not sure I understand the lines
Code:
// If there was a space, and if the current char is a letter
if(space && isalpha( string1.at(i) ) )
{
string1[i] = toupper( string1.at(i) );
space = false;
}
Am I understanding correctly that bool "space" was initialized as false earlier? So its value is set to 0. And doesn't AND operator only produce true value is both operands are equal to 1?
I'm sorry I misunderstood your requirements. I wrote that thinking you needed the first letter of every word capitalized. If YOU want A string LIKE this, you might want to dispense with the Boolean value, and just use an integer. Spaces aren't a thing you need to keep track of, just skip them. The only thing you need to keep track of is the word count.
Increment an integer every time your loop detects the first letter of every word, then depending on if the count is even or odd, you can treat that segment differently:
Code:
for(i=0;i<string1.length();i++)
{
//get a character
nextChar=string1.at(i);
// Skip all spaces.
if(isspace(nextChar))
{
continue;
}
else if( isalpha( nextChar ) )
{
// wordCount starts at 0, and is incremented every time you find a letter.
wordCount++;
// The capitalization condition with loop for every other word.
if( wordCount % 2 )
{
// Loop until next space, capitalizing letters.
while( i < string1.length() && !isspace( string1.at( i ) ) )
{
string1[i] = toupper( string1.at( i ) );
i++;
}
}
else
{
// Skip to either end of line or next space
while( i < string1.length() && !isspace( string1.at( i ) ) )
{
i++;
}
}
}
}
Alternatively, you could use a bool I believe, and just flip it's value every time you find a word.