面试题 - 字符串逆序

来源:互联网 发布:ie10 淘宝图片不显示 编辑:程序博客网 时间:2024/05/24 15:42
#include <string>#include <cstdlib>#include <cstdio>using namespace std;void reverseWord(char* word){    char* p = word;    while(*p != '\0')    {        p++;    }    --p;    while(p > word)    {        *p = *p ^ *word;        *word = *p ^ *word;        *p = *p-- ^ *word++;    }}void reverseBetween(char* p, char* q){    while(p < q)    {        *p = *p ^ *q;        *q = *p ^ *q;        *p = *p++ ^ *q--;    }}void reverseSentence(char *sen){    char* p = sen;  //word fisrt char    char* q = sen;  //word last char    while(*q != '\0')    {        if(*q == ' ')        {            reverseBetween(p, q-1);  //逆序单词            q++;            p = q;        }        else            q++;    }    reverseBetween(p, q-1);  //逆序最后一个单词    reverseBetween(sen, q-1);  //将整个句子逆序}int main(){    char str[] = "Hello, I am glad to see you!";    char s[] = "hello";    reverseWord(s);    reverseSentence(str);    printf("%s\n", s);    printf("%s\n", str);    return 0;}

0 0