翻转句子中单词的顺序

时间:2023-01-08 11:43:45

题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。句子中单词以空格符隔开。

比如:输入字符串: hello wolrd, welcome to china!

          逆序后的结果:china! to welcome wolrd, hello

算法思想:首先将整个句子逆序,得到!anihc ot emoclew ,drlow olleh 然后分割每个单词,把每个单词逆序得到最终结果

源代码:

/*

sentence: 字符串

first: 字符串的起始位置

last: 字符串的结束位置

*/

void reverse(string &sentence, int first, int last)
{

int i = first;

char temp;

int j = 0;


//首尾字符交换

while(i < (first + (last - first) / 2))

{

temp = sentence[i];

sentence[i] = sentence[last - 1 - j];

sentence[last - 1 -j] = temp;


++i;

++j;

}

}
void reverseWords(string &sentence)
{

//把整个字符串逆序

reverse(sentence, 0, sentence.length());


int i = 0;

int j = i;

//把单个单词逆序

while(i < sentence.length())

{

if(sentence[i] == ' ')

{

reverse(sentence, j, i);

j = i+1;

}

++i;

}

//逆序最后一个单词

reverse(sentence, j, i);

}

int main()
{

string sentence;

cout << "input a sentence: ";

getline(cin, sentence);


cout << "sentence is: " << sentence << endl;


reverseWords(sentence);


cout << "After reverse words, the result is:" << sentence << endl;


system("Pause");

return 0;

}