//字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”
//另外一种较为浪费空间的思路就是新建一个数组。。一个个判断空格就替换成%20
#include <stdio.h>
//#include <assert.h>
void replace(char *src)
{
//assert(src); //检查字符串定义
int OldLen = 0; //原字符串长度
int NewLen = 0; //新字符串长度
int BlackNum = 0; //空格数量
int NewBack = 0; //新字符串尾部
int OldBack = 0; //原字符串尾部
while (src[OldLen] != '\0')
{
if (src[OldLen] == ' ')
{
BlackNum++;
}
OldLen++;
}
NewLen = OldLen + BlackNum * 2;
OldBack = OldLen-1;
NewBack = NewLen - 1;
while (OldBack!=0)
{
if (src[OldBack] == ' ')
{
src[NewBack--] = '0';
src[NewBack--] = '2';
src[NewBack] = '%';
}
else
{
src[NewBack] = src[OldBack];
}
OldBack--;
NewBack--;
}
}
int main()
{
char p[20] = "hello world !";
replace(p);
printf("%s\n", p);
return 0;
return 0;
}
字符串替换
最新推荐文章于 2023-02-17 16:48:39 发布