【C语言】字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/doudouwa1234/article/details/46753439
//字符串替换空格:实现一个函数,把字符串里的空格替换成“%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;
}

展开阅读全文

没有更多推荐了,返回首页