Chinaunix首页 | 论坛 | 博客
  • 博客访问: 623179
  • 博文数量: 263
  • 博客积分: 9025
  • 博客等级: 中将
  • 技术积分: 2557
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-01 17:42
文章分类

全部博文(263)

文章存档

2012年(4)

2011年(64)

2010年(47)

2009年(44)

2008年(99)

2007年(5)

我的朋友

分类: C/C++

2011-04-15 16:11:50

原题:

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

思路:

原字符串: The house is blue

先翻转整个字符串-> eulb si esuoh ehT

再翻转单个单词。

代码:


#include
#include
#include

#define REVERSE_WORD(p1, p2) while (p1 <= p2) \
    { \
        char ch; \
        ch = *p1; *p1 = *p2; *p2 = ch; \
        p1++; p2--; \
    }

/*
 *  name: reverse_src_word_by_word
 *  params:
 *    des           [out]           输出字符串, des 指向实现申请的空间
 *    src           [in]            输入字符串,需要处理的字符串
 *  return:
 *    处理完成后的 des 指针
 *  notes:
 *    以单词为最下单位翻转字符串
 *    优化: 先翻转整个字符串,再翻转单个单词
 * 
 *  author: A.TNG 2006/06/16 10:37
 */
char * reverse_str_word_by_word2(char *src)
{
    char   *p1, *p2;
    int     n_src_len;

    if (NULL == src)
        return NULL;

    /* 先把整个字符串翻转一次 */
    n_src_len = strlen(src);
    p1 = src; p2 = src + n_src_len - 1;
    REVERSE_WORD(p1, p2);

    /* 再翻转单个单词 */
    p1 = src; p2 = p1;
    while ('\0' != *p2)
    {
        if (' ' == *p2)
        {
            char   *p;

            p = p2 - 1;
            REVERSE_WORD(p1, p);
            p2++;
            p1 = p2;
        }
        else
        {
            p2++;
        }
    }

    /* 翻转最后一个单词 */
    p2--;
    REVERSE_WORD(p1, p2);
    return src;
}


int main()
{
    // char src[] = " All-in-one ";
    // char src[] = "The house is blue";
    char    src[]   = "Zed is dead";

    (void) reverse_str_word_by_word2(src);
    printf("*****%s*****\n", src);

    system("PAUSE");
}

阅读(602) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~