剑指offer 2替换空格 c++和python
题目
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
c++版
class Solution {
public:
void replaceSpace(char *str,int length) {
string res = "";
for(int i = 0;i < length;++i){
if(str[i]==' '){
res = res + "%20";
}
else{
res = res + str[i];
}
}
return res;
}
};
其实上面代码的这个逻辑是可以的,把void
改成返回值为string
,但是他要求返回值为空,也就是直接修改原来的字符串
class Solution {
public:
void replaceSpace(char *str,int length) {
string res(str); //字符数组变string
int i = 0;
while(res.find(' ')!=string::npos){ //如果找到空格
i = res.find(' '); //空格所在位置
res.erase(i,1); //删除这个空格
res.insert(i,"%20"); //在这个位置插入 %20,然后继续查找空格
}
auto s = res.c_str(); //c_str()函数返回一个指向字符数组的指针常量, 内容与本res这个string串相同。注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针。
strcpy(str,s);
}
};
python版
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
temp = s.replace(' ',"%20")
return temp
# write code here
或者和c++一样,一个个替换
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
res = ''
for char in s:
if char == ' ':
res += '%20'
else:
res += char
return res
# write code here