面试题 - 字符串逆序

#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;
}

你可能感兴趣的:(面试题 - 字符串逆序)