替换空格(从后往前依次替换的思想)

请实现一个函数,把字符串中每个空格替换为“%20”,例如输入“I love you",则输出”I%20love%20you"。

void ReplaceBlank(char string[], int length)
{
	if (string == NULL || 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--;
	}
}


你可能感兴趣的:(替换空格(从后往前依次替换的思想))