剑指offer(4)替换空格

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zpxyklmwjlq/article/details/79959697

本算法方法来自于剑指offer,并牛客网编程通过

#include<iostream>
using namespace std;
class Solution {
public:
	void replaceSpace(char *str, int length)
	{
		if (str == NULL || length <= 0)
			 return;
		int originallength = 0;
		int numberofblank = 0;
		int i=0 ;
		while(str[i]!= '\0')
		{
			++originallength;
			if (str[i] == ' ')
				++numberofblank;
			++i;
		}//计算字符串长度,空格数量
		int newlength = originallength + 2 * numberofblank;//计算增加空格后的长度
		if (newlength > length)
			return;
		int indexoriginal = originallength;
		int indexnew = newlength;
		while (indexoriginal >= 0 && indexnew > indexoriginal)
		{
			if (str[indexoriginal] == ' ')
			{
				str[indexnew--] = '0';
				str[indexnew--] = '2';
				str[indexnew--] = '%';
			}//添加%20
			else
			{
				str[indexnew--] = str[indexoriginal];//原始字符向后移
			}
			--indexoriginal;
		}
		cout << str << endl;
	}
};
int _tmain()
{
	int length = 30;
	cout << "intput string: ";
	char str1[20];
	cin.get(str1, 20);//cin.get(字符数組名,接收字符数目)用來接收一行字符串,可以接收空格
	Solution S;
	S.replaceSpace(str1, length);
	system("pause");
	return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页