Title Description
The words were inverted sentence, punctuation is not upside down. . For example, I like beijing after the function becomes:. Beijing like I
Enter a description:
Each test comprises a test input:. I like beijing embodiment the input length not exceeding 100
Output Description:
After sequentially inverted output string, separated by spaces
Example 1
Input: I like beijing.
Output: beijing like I.
Thinking 1 : substr by the first string into a word into a vector, the vector and then in reverse order output words, to complete the inverted string
codes:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
int main()
{
while (1)
{
string str;
getline(cin, str);
vector<string> v;
int pos = 0, start = 0;
while(pos<str.size())
{
pos = str.find(' ', start);
string ret = str.substr(start, pos - start);
v.push_back(ret);
start = pos + 1;
}
vector<string>::reverse_iterator it = v.rbegin();
while (it != v.rend())
{
cout << *it << " ";
it++;
}
cout << endl;
}
system("pause");
return 0;
}
2 ideas : first complete flip an entire string, and then complete the partial reversal, that is to stop after finding space, complete flip.
Code:
#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;
system("pause");
return 0;
}