《剑指offer》—— 02_替换空格
题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
[解题思路]
1.从前到后进行遍历查找字符串空格数目,并计算字符串长度;
2.替换则是从后到前进行,原因:若从前到后,当遇到第一个空格时,空格后的所有字符需要往后移动;当遇到第二个空格时,空格后的所有字符需往后移动……以此类推,复杂度高。采取从后到前查找替换时,只需移动较少步数,效率高。
[测试代码]
1.头文件
#pragma once
#ifndef REPLACSPACE_H_
#define REPLACESPACE_H_
#include<string>
class Solution
{
public:
void replaceSpace(char *str, int length)
{
//遍历字符串,查找空格数量
if (str == NULL && length<0)
return;
int oldnumber = 0;//记录以前的长度
int spacenumber = 0;//记录空格数量
int i = 0;
while (str[i] != '\0')
{
oldnumber++;
if (str[i] == ' ')
spacenumber++;
i++;
}
int newlength = oldnumber + spacenumber * 2;//新字符串长度=旧字符串长度+空格数*(新增的3个字符-原有的一个空格:3-1)
if (newlength > length)//新字符串长度大于总长度,无效
return;
int pOldlength = oldnumber;//注意不要减一,原因:‘\0’也要加入
int pNewlength = newlength;
while (pOldlength >= 0 && pNewlength > pOldlength)
{
if (str[pOldlength] == ' ')//碰到空格就替换
{
str[pNewlength--] = '0';
str[pNewlength--] = '2';
str[pNewlength--] = '%';
}
else//不是空格,就将pOldlength指向的字符装入pNewlength指向的位置
{
str[pNewlength--] = str[pOldlength];
}
pOldlength--;
}
}
};
#endif
2.主函数
#include"ReplaceSpace.h"
#include<iostream>
int main()
{
using std::cout;
using std::endl;
char a[13] = { "we are happy" };
Solution st;
st.replaceSpace(a,100);
cout << a;
getchar();
system("pause");
return 0;
}
3.运行结果
[考察知识点]
本题考察的主要是字符串知识。