- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Can you think of an algorithm that performs the below:
“The Big Brown Fox” => “Fox Brown Big The”
“How are you?” => “you? are How”
std::string reverse_words( const std::string& str )
{
std::string result;
result.reserve( str.length() );
size_t word_begin = 0;
while( word_begin < str.length() )
{
const size_t pos = str.find_first_of( ' ', word_begin );
pos = (pos != string::npos) ? pos : str.length();
std::string word = str.substr( word_begin, pos-word_begin );
word_begin = pos + 1;
if (result.length() > 0)
{
word.append( 1, ' ');
}
result.insert( 0, word );
}
return result;
}