题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解答:这题比较常规,没什么技术含量
答案:
class Solution {
public:
void replaceSpace(char *str,int length) {
for(int i = 0; i < length; ++i)
{
if(str[i] == ' ')
{
for (int j = length+1; j > i+2; --j) {
str[j] = str[j-2];
}
str[i] = '%';
str[i+1] = '2';
str[i+2] = '0';
}
}
}
};
优化思路(直接调用函数):
class Solution {
public:
void replaceSpace(char *str,int length) {
string my_str = str;
if (my_str.empty())
return;
while (my_str.find(" ") != string::npos)
{
my_str.replace(my_str.find(" "),1,"%20");
}
//这样cpy是不行的
//char *newchar = new char(my_str.size());
//strcpy(newchar,my_str.c_str());
char nchar[my_str.size()];
strcpy(nchar,my_str.c_str());
str = nchar; //不知道为什么传不出去
cout<<str<<endl;
}
};
int main()
{
Solution solution;
char *str = "We Are Happy";
solution.replaceSpace(str,12);
cout<<str<<endl;
return 0;
}
优化思路(从后往前复制)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>
using namespace std;
class Solution {
public:
void replaceSpace(char *str,int length) {
int count = 0;
int i = 0;
int origin_len = 0;
while (str[i] != '\0')
{
origin_len++;
if (str[i] == ' ')
count++;
i++;
}
int p1,p2;
p1 = origin_len;
p2 = p1 + count*2;
if (p2 > length)
return;
// cout<<"p1:"<<p1<<" p2:"<<p2<<endl;
for (int j = 0; j < origin_len + 1; ++j) {
if (str[p1] == ' ')
{
str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';
} else{
str[p2--] = str[p1];
}
p1--;
}
//string m_str = str;
}
};
int main()
{
Solution solution;
//如果这样传参数会发生段错误
//char * my_str = "We Are Happy.";
char my_str[100] = "We Are Happy.";
solution.replaceSpace(my_str,100);
cout<<*my_str<<endl;
return 0;
}