Python/C++ realize sentence reversal

Title description

Given a sentence (containing only letters and spaces), reverse the position of the words in the sentence, split the words with spaces, and there is only one space between the words, and no spaces before and after.

such as:

(1).  “hello everyone”-> “everyone hello”

python code:

sen1 = input('请按要求输入句子:')
sen2 = sen1.split(' ')
print(' '.join(sen2[::-1]))

C++ code:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    
    
	string str;
	getline(cin, str);
	reverse(str.begin(), str.end());
	int i = 0, j = i;
	while (j < str.size()) {
    
    
		while (j < str.size() && str[j] != ' ') j++;
		reverse(str.begin() + i, str.begin() + j);
		j++;
		i = j;
	}
	cout << str << endl;
}

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/108469238