题目描述
将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
输入描述:
每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100
输出描述:
依次输出倒置之后的字符串,以空格分割
示例1:
输入
I like beijing.
输出
beijing. like I
思路1:
-
先将整个字符串逆置过来,
-
遍历字符串,找出每个单词,对单词逆置。
这里我们可以使用了stl算法中的 reverse
解答代码1:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str); // 注意这里要使用getline,cin>>s遇到空格就接收结束了
// 翻转整个句子
int start = 0;
int end = str.size() - 1;
for (start = 0; start < end; start++, end--) {
swap(str[start], str[end]);
}
// 翻转每个单词
end = 0;
while (end != str.size()) {
start = end;
while (str[end] != ' ' && end != str.size()) {
end++;
}
//找到空格
int tmp;
if (end != str.size()) {
tmp = end + 1;
}
else {
tmp = end;
}
--end;
for (; start < end; start++, end--) {
swap(str[start], str[end]);
}
end = tmp;
}
cout << str << endl;
return 0;
}
代码2
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s;
// 注意这里要使用getline,cin>>s遇到空格就接收结束了
getline(cin, s);
// 翻转整个句子
reverse(s.begin(), s.end());
// 翻转单词
auto start = s.begin();
while (start != s.end()) {
auto end = start;
while (end != s.end() && *end != ' ')
end++;
reverse(start, end);
if (end != s.end())
start = end + 1;
else
start = end;
}
cout << s << endl;
return 0;
}
思路2
第二思路是一个比较讨巧的思路,直接利用cin>>s接收输入,遇到空格就结束了,自然就分割开了每个单词,其次将每次接收到的单词拼接到之前串的前面就逆置过来了
题解代码:
#include <iostream>
#include <string>
using namespace std;
// cin读取string时自动会被空格分隔开,用另一个字符串存储进行逆序输出
int main()
{
string s1, s2;
cin >> s2;
while (cin >> s1)
s2 = s1 + " " + s2;
cout << s2 << endl;
return 0;
}
如有不同见解,欢迎留言讨论~~