翻转句子中单词的顺序

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

比如:输入字符串: 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值