将一个字符串中的所有空格替换为%20的源代码及测试用例

#include <iostream>
#include <assert.h>

void ReplaceBlank(char string[],int capacity)//capacity为数组str的总容量
{
	if (string == NULL || capacity <= 0)
		return;
	int length = 0;
	int blank_count = 0;
	int i = 0;
	while (string[i]!='\0')
	{
		length++;
		if (string[i] == ' ')
		{
			blank_count++;
		}
		i++;
	}

	int newLength = length + blank_count * 2;
	if (newLength > capacity)
		return;
	int indexOld = length;
	int indexNew = newLength;

	while (indexOld >= 0 && indexNew >= indexOld)
	{
		if (string[indexOld] == ' ')
		{
			string[indexNew--] = '0';
			string[indexNew--] = '2';
			string[indexNew--] = '%';
		}
		else
		{
			string[indexNew] = string[indexOld];
			indexNew--;
		}
		--indexOld;
	}
}


void Test(char* testName, char string[], int length, char expected[])
{
	if (testName != NULL)
		printf("%s begins: ", testName);

	ReplaceBlank(string, length);

	if (expected == NULL && string == NULL)
		printf("passed.\n");
	else if (expected == NULL && string != NULL)
		printf("failed.\n");
	else if (strcmp(string, expected) == 0)
		printf("passed.\n");
	else
		printf("failed.\n");
}

// 空格在句子中间
void Test1()
{
	const int length = 100;

	char string[length] = "hello world";
	Test("Test1", string, length, "hello%20world");
}

// 空格在句子开头
void Test2()
{
	const int length = 100;

	char string[length] = " helloworld";
	Test("Test2", string, length, "%20helloworld");
}

// 空格在句子末尾
void Test3()
{
	const int length = 100;

	char string[length] = "helloworld ";
	Test("Test3", string, length, "helloworld%20");
}

// 连续有两个空格
void Test4()
{
	const int length = 100;

	char string[length] = "hello  world";
	Test("Test4", string, length, "hello%20%20world");
}

// 传入NULL
void Test5()
{
	Test("Test5", NULL, 0, NULL);
}

// 传入内容为空的字符串
void Test6()
{
	const int length = 100;

	char string[length] = "";
	Test("Test6", string, length, "");
}

//传入内容为一个空格的字符串
void Test7()
{
	const int length = 100;

	char string[length] = " ";
	Test("Test7", string, length, "%20");
}

// 传入的字符串没有空格
void Test8()
{
	const int length = 100;

	char string[length] = "helloworld";
	Test("Test8", string, length, "helloworld");
}

// 传入的字符串全是空格
void Test9()
{
	const int length = 100;

	char string[length] = "   ";
	Test("Test9", string, length, "%20%20%20");
}

int main()
{
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();
	Test7();
	Test8();
	Test9();

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值