CTCI系列--1.4 字符替换(C语言)

题目:Write a method to replace all spaces in a string with '%20'.You may assume that the string has sufficient space at the end of the string to hold the additional characters,and that you are given the "true" length of the string.(Note:if implementing in Java,please use a character array so that you can perform this operation in place.) EXAMPLE Input: "Mr John Smith " Output:"Mr%20John%Smith" 写一个方法用'%20'替换字符串中的所有空格。你需要确保字符串有足够的空间来存储额外的字符,你被给与字符串的真实长度。(注意:如果用Java实现,请使用character array这样你可以执行这个操作。)


####解题思路 首先按照题目意思是将空格替换为'%20',但按照题目给的示例字符串末尾的空格并没有转换成'%20'。我们这里还是按照将**==所有==**空格都转换成'%20'来处理。

在字符串处理中有个通用的方法是从字符串的末尾开始往回处理,我们这里就使用这个方法。

步骤:

  • 获取字符串有效长度以及字符数组的总大小
  • 计算字符串中空格的数目
  • 计算替换空格后字符串的总长度并与字符数组大小比较。若超出字符数组大小则报错
  • 从字符串末尾开始将字符搬移到新的位置,若遇空格则替换为'%20'

####代码实现 算法代码与测试程序如下:

#include <stdio.h>
#include <string.h>

int replaceSpace(char *str, int totalLen)
{
	int newStrLen = 0;
	int originStrLen = 0;
	int spaceCount = 0;
	int i;

	originStrLen = strlen(str);

	for (i = 0; i < originStrLen; i++)
	{
		if (str[i] == ' ')
		{
			spaceCount++;
		}
	}

	newStrLen = originStrLen + spaceCount * 2;

	if (newStrLen + 1 > totalLen)
		return -1;
	str[newStrLen] = '\0';
	for (i = originStrLen - 1; i > 0; i--)
	{
		if (str[i] == ' ')
		{
			str[newStrLen - 1] = '0';
			str[newStrLen - 2] = '2';
			str[newStrLen - 3] = '%';
			newStrLen = newStrLen - 3;
		}
		else
		{
			str[newStrLen - 1] = str[i];
			newStrLen = newStrLen - 1;
		}
	}
	return 0;
}

#define BUFLENS  50
int main(void)
{
	char buf[BUFLENS] = "Mr John Smith   ";

	printf("%s\n", buf);

	replaceSpace(buf, BUFLENS);

	printf("%s\n", buf);

	getchar();
	return 0;
}

####运行结果

运行结果


文章转载自我的非鱼物语 本文固定链接为:http://linuxue.com/archives/20

转载于:https://my.oschina.net/undersky/blog/608735

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值