面试系列4以单词为最小单位翻转字符串

来源:软件水平考试    发布时间:2012-11-05    软件水平考试视频    评论

原题:
  以单词为最小单位翻转字符串
  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:    以单词为最小单位翻转字符串
                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 <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
 *  name: reverse_src_word_by_word
 *  params:
 *    des           [out]           输出字符串, des 指向实现申请的空间
 *    src           [in]            输入字符串,需要处理的字符串
 *  return:
 *    处理完成后的 des 指针
 *  notes:
 *    以单词为最下单位翻转字符串
 * 
 *  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 的最有一个字符开始遍历 */
    p1 = src + strlen(src) - 1;
    p2 = p1;
    psz_dest = des;
    while (p1 != src)
    {
        if (' ' == *p1)
        {
            int n_len;
            /* 找到一个单词,拷贝单词 */
            n_len = p2 - p1;
            memcpy(psz_dest, p1 + 1, n_len);
            psz_dest += n_len;
            *psz_dest++ = ' ';
            /* 准备寻找下一个单词 */
            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');
}

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答