您的位置:首页 > 其它

替换字符串中的空格

2016-05-29 21:35 288 查看
题目:实现一个函数,要求吧字符串中的所有空格替换成“%20”。
例如“we are happy."-->”we%20are%20happy."
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void strReplace(const char *dst, char *pun, const char *src);
int countSpace(const char *dst);

int main()
{
char dst[] = "I am a student.";
char src[] = "%520";
int space = countSpace(dst);
int len = strlen(dst) + (strlen(src) - 1)*space;
char *pun = (char *)malloc(len);
strReplace(dst, pun, src);
puts(pun);
system("pause");
return 0;
}

/*求字符串中空格的个数*/
int countSpace(const char *dst)
{
int count = 0;
while (*dst)
{
if (*dst == ' ')
{
count++;
}
dst++;
}
return count;
}

/*“we are happy.”“we%20are%20happy.”*/
void strReplace(const char *dst, char *pun, const char *src)
{
assert(dst);
assert(src);
while (*dst != '\0')
{
while (*dst != '\0' && *dst != ' ')
{
*pun = *dst;
pun++;
dst++;
}
char *start = src;
if (*dst == ' ')
{
while (*src)
{
*pun = *src;
pun++;
src++;
}
src = start;
dst++;
}
}
*pun = '\0';
}
运行代码:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/75/43/wKioL1Y0QMzy4FWPAABNfON8JjY737.jpg" title="{J9B4LEIWHTPYPA2Z8$NC)U.png" alt="wKioL1Y0QMzy4FWPAABNfON8JjY737.jpg" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: