0

I need help with a program that reverses the letters in a word without altering its order in a sentence.
Sample Input:
What a sunny day
Output should be:
tahW a ynnus yad

Thanks in advance!

3
Contributors
2
Replies
14
Views
2 Years
Discussion Span
Last Post by NathanOliver
0

Probably the most efficient way to do this is to look through the string, looking for whitespace. When you do, loop through the string from just before the whitespace back to the beginning of the word, outputing each character. Then output the whitespace, then set the beginning of the next word and keep going until you reach the end of the string. Where I say output, you could also append to a string then output the string all at once.

Edited by Nutster: Added another option.

0

I would split the string up into an vector of sub strings. Reverse each sub string in the vector. Then combine them all back together. You can easily split a string with spaces by using string streams:

std::stringstream ss;
string line = "What a sunny day";
std::vector<std::string> parts;
string temp;

ss << line;  // load the stream
while (ss >> temp)  extract untill space or end
{
    parts.push_back(temp);
    temp.clear();  // erase temp to fill again
}

// now parts[0] = What, parts[1] = a, parts[2] = sunny, parts[3] = day
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.