字符串以空格翻转

将以空格为分隔符分隔的字符串逆序打印,但单词不逆序。例如“Hello world Welcome to China”的打印结果为“China to Welcome world Hello”。
#include <stdio.h>
#include <string.h>
/* Print string str partially, from start to end-1. */
void print_word(const char * str, int start, int end)
{
int i;
    for (i = start; i < end; ++i)
{
printf("%c", str[i]);
}
}
/* Reversely print string str. */
void reversely_print_string(const char * str)
{
int len, i, end;
    len = strlen(str);
end = len;
for (i = len - 1; i >= 0; --i)
{
if (' ' == str[i])
{
/* Print the word after this space. */
print_word(str, i + 1, end);
            /* Print the space. */
printf("%c", str[i]);
            /* Set the right boundary of the previous word. */
end = i;
}
}
/* Print the first word. */
print_word(str, 0, end);
}
int main(int argc, char * argv[])
{
if (argc > 1)
{
reversely_print_string(argv[1]);
}
printf("\n");
    return 0;
}

这个方法是直接翻转法、遇到空格就把后面的串输出,只用一个end就行了

 

posted @ 2013-10-25 13:53  夜雨阑珊  阅读(687)  评论(0编辑  收藏  举报