Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
"
void reverseWords(string &s) {
vector<string> vec;
string word;
stringstream stream(s);
while(stream >> word)//这种萃取方法很好用,亦可用stringstream 进行类型转换!
{
vec.push_back(word);
}
s.clear();//s = "";
if(vec.size() == 0)return ;
vector<string>::reverse_iterator iter = vec.rbegin();
for(;iter != (vec.rend() - 1);iter++)
{
s += *iter+ " ";
}
s += *iter;
return ;
}
此题将提取的东西存在了vector,再通过反向迭代器处理。
注意“ ” 或“” 的情况即可!
补充思路:2014-3-30 21:30
推荐:http://www.geeksforgeeks.org/reverse-words-in-a-given-string/
//此种思路适合在原字符串上直接操作但是,对于开头中间无空格的情况!
否则任然需提取出字符串!!!
本题为: 先对串中word转置,之后对整个串转置! ----》一直常用思路。 比如字符串的某一部分翻转到前面。st1 st2 ----> st2 st1 情况!
void reverse_word(string &str)
{
if (str.empty())
{
return ;
}
int i = 0;
int word_begin = 0;
int word_end = 0;
bool all_space_flag = true;
while(i < str.length())
{
while(str[i] == ' '&&i < str.length())
{
i++;
}
if (i == str.length())//全为空格串
{
if (true == all_space_flag)
{
str = "";
return;
}
break;
}
all_space_flag = false;
word_begin = i;
while(str[i] != ' '&&i < str.length())
{
i++;
}
word_end = i-1;
reverse(&str[word_begin],&str[word_end]);
}
reverse(&str[0],&str[str.length()-1]);
return;
}
void reverse(char *s ,char *e)//区间
{
char temp;
while(s < e)
{
temp = *s;
*s = *e;
*e = temp;
s++;
e--;
}
}