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

原题:

  以单词为最小单位翻转字符串
  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");
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值