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