将字符串中的空格用 代替

将字符串“we are happy”转换为“we%20are%20happy”


#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<ctype.h>
void My_Replace(char *arr)
{
	char *start = arr;//"we are happy\0"start指向字符串首地址
	char *end = NULL;
	int old_len = 0;//计算代替前字符串的长度
	int space_nums = 0;//空格的数目
	assert(arr);//判断arr是否为空
	
	while (*start != '\0')
	{
		if (isspace(*start))//如果start指向空格
		{
			space_nums++;
		}
	    start++;//指向下一个元素
		old_len++;
	}
	//start指向了字符串"we are happy\0"的\0
	end = arr +old_len+ 2 * space_nums;//we%20are%20happy\0,end指向\0

	while (start < end )
	{
		if (isspace(*start))//如果start指向空格时,用%20替换空格
		{
			*end-- = '0';
			*end-- = '2';
			*end = '%';
		}
		else
		{
			*end = *start;//如果start指向的不是空格,则将字符后移
		}
		start--,end--;
	}
}

int main()
{
	char str[60] = "we are happy";
	My_Replace(str);
	printf("%s\n",str);
	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值