实现字符串中单词顺序的逆置

来源:互联网 发布:河南青峰网络 编辑:程序博客网 时间:2024/05/20 02:27

比如 i love you 变换为you love i

#include "string"#include "iostream"using namespace std;void ReverseWord(char* p, char* q){char temp=NULL;while(p<q){temp=*p;*p=*q;*q=temp;p++;q--;}}void ReverseSentence(char *str){char *p=str;char* q=p;while ('\0'!=*q){if (*q==' '){ReverseWord(p,q-1);q++;p=q;}elseq++;}//实现最后一个单词的逆反ReverseWord(p,q-1);//实现整个句子的逆反ReverseWord(str,q-1);}int main(){char str[] = "i love you very much";cout << str << endl;ReverseSentence(str);cout << str << endl;return 0;}

0 0