将一个字符串按单词逆序

1. 给定一个字符串,按单词将该字符串逆序,如输入"hello world",输出为"world hello"。方法:先按单词逆序,再对整个句子逆序。

2. 附加: 将整个字符串逆序。


#include
#include


int reverse_word(char *p, char *q)
{
    while(p < q)
    {
        *p = *p^*q;
        *q = *p^*q;
        *p = *p++^*q--;
    }
    return 0;
}


void reverse_only_string(char *s)
{
    char *p = s;
    while(*p++ != '\0')
        ;
    //p--;
    reverse_word(s, p-2);
}


void reverse_sentence(char *s)
{
    int i = 0;
    char *p;
    char *q;
    p = q = s;
    while(*q !='\0')
    {
        if(*q == ' ')
        {
            reverse_word(p, q-1);
            q++;
            p = q;
        }
        else
            q++;
    }
    reverse_word(p, q-1);
    //q--;
    reverse_word(s, q-1);

}


int main()
{
    char s1[] = "hello world";
    char s2[] = "hello world";
    char *p;
    printf("before reverse, original string as below:\n");
    printf("%s\n", s1);
    reverse_only_string(s1);
    printf("after reverse only word, reversed string as below:\n");
    printf("%s\n", s1);
    reverse_sentence(s2);
    printf("after reverse, reversed string as below:\n");
    printf("%s\n", s2);
    return 0;
}

你可能感兴趣的:(C++,数据结构)