题目:实现一个函数,要求吧字符串中的所有空格替换成“%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';
}
运行代码: