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

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

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

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

位律师回复
DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
白度搜_经验知识百科全书 » 面试系列4以单词为最小单位翻转字符串

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情