用“ ”替代string中所有的空格

solution

如果有足够的空间,可以开辟另外一个char数组,当遇到空格时,将空格替换为"%20"然后存入数组。

char str[1000];

如果没有多余的空间,假设原str数组足够大,可以遍历str数组,求出空格的个数spaceCount,根据空格的个数算出需要增加的空间数:spaceCount*2。然后从后边遍历原数组,遇到空格时进行替换,并放入原数组的后边。

The algorithm is as follows:1. Count the number of spaces during the first scan of the string.2. Parse the string again from the end and for each character:»» If a space is encountered, store “%20”.

»» Else, store the character as it is in the newly shifted location.

假设数组在后边有足够的空间

// Assume parsed string has sufficient free space at the end
ReplaceFun(char * str, int length) {
	int SpaceCount = 0, NewLength, i=0;
//计算空格数目
	for (i = 0; i < length; i++) {
		if (str[i] == ’ ‘) {
		SpaceCount++;
		}
	}
//重新计算需要的空间数目
	NewLength = length + SpaceCount * 2;
	Str[NewLength] = ‘\0’;
//从后面开始写入新数据
	for (i = length — 1; i >= 0; i--) {
		if (str[i] == ‘ ‘) {
			str[NewLength -1 ] = ‘0‘;
			str[NewLength -2 ] = ‘2’;
			str[NewLength -3 ] = ‘%’;
			NewLength = NewLength -3;
		} else {
			str[NewLength - 1] = str[i];
			NewLength = NewLength -1;
			}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值