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

题目:请实现一个函数,把字符串中的每个空格替换成"%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;
}

猜你喜欢

转载自blog.csdn.net/weixin_39916039/article/details/82109842
今日推荐