Fork me on GitHub

单词翻转

问题描述:输入一个英文句子,翻转句子中单词的顺序。要求单词内字符顺序不变,句子中单词由空格隔开。为简单起见,标点符号和普通字母一样处理。例如,若输入"I am a student.",则输出"student. a am I"

参考思路:首先将整个字符串进行翻转,然后根据空格来实现每个单词的翻转,关键在于判断结束为止以及下一个单词的开始位置。

参考代码:

#include <bits/stdc++.h>

using namespace std;

void swap_str(char* a, char* b)
{
    char t = *a;
    *a = *b;
    *b = t;
}

void str_reverse(char *start, char *over)
{
    while (start < over)
    {
        swap_str(start++, over--);
    }
}

void reverseString(char *s)
{
    char *start = s;
    char *over  = start;

    for ( ; *over!= '\0'; over++ )
    {
    };
    over--;

    str_reverse( start, over );
    start = s;
    over  = start;
    char* end_word = NULL;

    while ( *(over-1) != '\0' )
    {
        if (*over == ' '|| *over == '\0')
        {
            end_word = over-1;
            str_reverse(start, end_word);
            start = over;
            while(*start == ' ')
            {
                start++;
            }
        }
        over++;
    }
}

int main()
{
    char str[] = "I am  a    student.";
    reverseString(str);
    printf("%s\n", str);
}

GCC运行结果:

 

posted @ 2016-03-28 20:55  伊甸一点  阅读(620)  评论(0编辑  收藏  举报