字符串-----替换空格

题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。

方法:从后往前替换,先求出字符串总长度、空格数、新字符串长度,然后两个指针分别指向原始字符串末尾和新字符串末尾,依次替换,遇到空格时则替换为"0" "2" "%".

#include <cstdio>
#include<cstring>

void ReplaceBlank(char string[], int length)
{
	if (string == nullptr&&length <= 0)
		return;
	int originalLength = 0;
	int numberOfBlank = 0;
	int i = 0;
	while (string[i] != '\0')
	{
		++originalLength;
		if (string[i] == ' ')
			++numberOfBlank;
		++i;
	}
	int newLength = originalLength + numberOfBlank * 2;
	if (newLength > length)
		return;
	int indexOfOriginal = originalLength;
	int indexOfNew = newLength;
	while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
	{
		if (string[indexOfOriginal] == ' ')
		{
			string[indexOfNew--] = '0';
			string[indexOfNew--] = '2';
			string[indexOfNew--] = '%';
		}
		else
			string[indexOfNew--] = string[indexOfOriginal];
		--indexOfOriginal;
	}
}
//测试用例
//正常输入
void Test1()
{
	const int length = 100;
	char str[length] = "we are happy.";
	ReplaceBlank(str, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
//输入没有空格
void Test2()
{
	const int length = 100;
	char str[length] = "wearehappy.";
	ReplaceBlank(str, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
//连续两个空格
void Test3()
{
	const int length = 100;
	char str[length] = "we  arehappy.";
	ReplaceBlank(str, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
//空格在最后
void Test4()
{
	const int length = 100;
	char str[length] = "we are happy. ";
	ReplaceBlank(str, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
//输入空指针
void Test5()
{
	const int length = 100;
	char str[length] = "we are happy. ";
	ReplaceBlank(nullptr, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
//输入一个空格
void Test6()
{
	const int length = 100;
	char str[length] = " ";
	ReplaceBlank(str, length);
	int j = 0;
	while (str[j] != '\0')
	{
		printf("%c ", str[j++]);
	}
	printf("\n");
}
int main()
{
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值