將語句單詞反轉

題目:將語句的單詞反轉, I am chinese 輸出 chinese am I,不能開闢非常量存儲空間

算法:先將每個單詞反轉,再整體反轉一次。題很簡單,但這個思路一般人不好往這個方向想。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

inline void swap(char* p1, char* p2)    //交換
{
        char c = *p1;
        *p1 = *p2;
        *p2 = c;
}

void turn(char* str, int len)                   //翻轉
{
        int i;
        for(i = 0; i < len / 2; i++)
                swap(str + i, str + len - 1 - i);
}

void turn_words(char* str)                              //  語句單詞翻轉
{
        char* p = str;
        char* beg = p;
        while(*p != '\0')
        {
                if(*p == ' ')
                {
                        turn(beg, p - beg);                     //翻轉每個單詞
                        beg = ++p;
                }
                else
                        ++p;
        }
        turn(beg, p - beg);                                     //最後一個單詞
        turn(str, strlen(str));                         //整個字符串翻轉一次
}

int main()
{
        char* s = (char*)malloc(1024);
        while(scanf("%[^\n]\n", s) == 1)
        {
                turn_words(s);
                printf("%s\n", s);
        }
        free(s);
        return 0;
}
echo "When nine is divided by four the quotient is two with a remainder of one" | ./binm
one of remainder a with two is quotient the four by divided is nine When

發佈了87 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章