分类: 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");
}