剑指Offer:替换空格(C/C++)

替换空格
题目:实现一个函数,把字符串中的每个空格替换成%20,例如:输入"hello world!",输出"hellp%20world!"

  • C语言实现:
void ReplaceBlank(char str[], int length)
{
	int len = length;
	int i = 0;
	int NumberBlank = 0;
	if (length <= 0 || str == NULL)
		return;
	for (; i < len; i++) //求空格个数
	{
		if (str[i] == ' ')
			NumberBlank++;
	}
	int Newlength = length + NumberBlank * 2; //新字符串长度
	int IndexOfOrigina = length - 1; //原末尾
	int IndexOfNew = Newlength - 1;  //新末尾
	while (IndexOfOrigina > 0 && IndexOfNew > IndexOfOrigina)
	{
		if (str[IndexOfOrigina] == ' ')  //处理空格
		{
			str[IndexOfNew--] = '0';
			str[IndexOfNew--] = '2';
			str[IndexOfNew--] = '%';
		}
		else
		{
			str[IndexOfNew--] = str[IndexOfOrigina];
		}
		IndexOfOrigina--;
	}
}
int main()
{
	char str[32] = "How are you";
	int length = strlen(str) + 1;
	int i = 0;
	int j = 0;
	for (; i < length; i++)
		printf("%c", str[i]);
	printf("\n");
	ReplaceBlank(str, length);
	int Newlength = sizeof(str);
	for (; j < Newlength; j++)
		printf("%c", str[j]);
	printf("\n");
	system("pause");
	return 0;
}

运行代码:

 

  • C++实现:
class Solution {
public:
	void replaceSpace(char *str,int length) 
    {
        if(length <= 0 || str == NULL)   
            return;
        int count = 0;
        for(int i = 0;i<length;i++)   //计算空格数
        {
            if(str[i] == ' ')
                ++count;
        }
        int NewLength = length + count*2;   //注意空格数要乘2
        int Origina = length -1;  //数组元素下标-1
        int New = NewLength -1;
        while(New >= Origina && Origina >= 0)
        {
            if(str[Origina] == ' ')     //替换空格
            {
                str[New--] = '0';
                str[New--] = '2';
                str[New--] = '%';
                Origina--;
            }
            else
                str[New--] = str[Origina--];
        }
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值