《剑指Offer》面试题5

 

1 问题描述

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

 

2 代码

#include "iostream"

using namespace std;

//功能:替换字符串中的空格
//输入:str字符数组
//返回:true成功
bool ReplaceBlank(char* str, int length)
{
	if ((str == nullptr) || (length <= 0))
	{
		return false;
	}
	//实际字符串长度和空格数量
	int originalLength = 0;
	int numberOfBlank = 0;

	int i = 0;
	while (str[i] != '\0')
	{//1.遍历数组,统计字符串实际长度和空格个数
		if (str[i] == ' ')
		{
			numberOfBlank++;
		}
		originalLength++;
		i++;
	}

	//2.计算新字符串长度
	int NewLength = originalLength + numberOfBlank*2;
	if (NewLength > length)
	{
		return false;
	}

	//3.两个指针,一个指向原字符串尾部,另一个指向新字符串尾部
	int OriginIndex = originalLength;
	int NewIndex = NewLength;
	while ((OriginIndex >= 0) && (NewIndex > OriginIndex))
	{//4.从字符串尾部进行操作,从后向前替换
		if (str[OriginIndex] == ' ')
		{
			str[NewIndex--] = '0';
			str[NewIndex--] = '2';
			str[NewIndex--] = '%';
		}
		else
		{
			str[NewIndex--] = str[OriginIndex] ;
		}
		OriginIndex--;
	}
	return true;
}

void test01()
{
	char str[30] = "hello world !!";
	ReplaceBlank(str, sizeof(str)/sizeof(char));
	cout << "res:" << str << endl;
}

int main(int argc, char const *argv[])
{
	test01();
	return 0;
}