面試系列4以單詞為最小單位翻轉(zhuǎn)字符串

字號(hào):

原題:
     以單詞為最小單位翻轉(zhuǎn)字符串
     write the function string reversestringwordbyword(string input) that reverses
     a string word by word. for instance,
     reversestringwordbyword('the house is blue') --> 'blue is house the'
     reversestringwordbyword('zed is dead') --> 'dead is zed'
     reversestringwordbyword('all-in-one') --> 'all-in-one'
    代碼:
    /********************************************************************
     created: 2006/06/16
     filename: c:/documents and settings/administrator/桌面/flwo/reverse.c
     file path: c:/documents and settings/administrator/桌面/flwo
     file base: reverse
     file ext: c
     author: a.tng
     version: 0.0.1
     purpose: 以單詞為最小單位翻轉(zhuǎn)字符串
     write the function string reversestringwordbyword(string input)
     that reverses a string word by word. for instance,
     reversestringwordbyword('the house is blue') --> 'blue is house the'
     reversestringwordbyword('zed is dead') --> 'dead is zed'
     reversestringwordbyword('all-in-one') --> 'all-in-one'
    *********************************************************************/
    #include
    #include
    #include
    /*
     * name: reverse_src_word_by_word
     * params:
     * des [out] 輸出字符串, des 指向?qū)崿F(xiàn)申請(qǐng)的空間
     * src [in] 輸入字符串,需要處理的字符串
     * return:
     * 處理完成后的 des 指針
     * notes:
     * 以單詞為最下單位翻轉(zhuǎn)字符串
     *
     * author: a.tng 2006/06/16 9:06
     */
    char *reverse_str_word_by_word(char *des, char *src)
    {
     char *p1, *p2;
     char *psz_dest;
     if ((null == des) || (null == src))
     return null;
     /* 從 src 的最有一個(gè)字符開(kāi)始遍歷 */
     p1 = src + strlen(src) - 1;
     p2 = p1;
     psz_dest = des;
     while (p1 != src)
     {
     if (' ' == *p1)
     {
     int n_len;
     /* 找到一個(gè)單詞,拷貝單詞 */
     n_len = p2 - p1;
     memcpy(psz_dest, p1 + 1, n_len);
     psz_dest += n_len;
     *psz_dest++ = ' ';
     /* 準(zhǔn)備尋找下一個(gè)單詞 */
     p1--; p2 = p1;
     }
     else
     {
     /* p1 往前移一位 */
     p1--;
     }
     }
     /* 最后一次拷貝單詞 */
     if (p1 != p2)
     {
     int n_len;
     n_len = p2 - p1 + 1;
     memcpy(psz_dest, p1, n_len);
     psz_dest += n_len;
     *psz_dest = '/0';
     }
     return des;
    }
    /*
     * name: main
     * params:
     * none
     * return:
     * none
     * notes:
     * none
     *
     * author: a.tng 2006/06/16 9:08
     */
    int main()
    {
     char des[100] =
     {
     0
     };
     char *src = 'the house is blue';
     (void) reverse_str_word_by_word(des, src);
     printf('*****%s*****/n', des);
     system('pause');
    }