替换空格(python)

时间:2024-01-03 20:59:02

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
i=0
n=len(s)
ss=[]##初始化定义算法的中间变量
for i in range(n):
if s[i].isspace():
ss.append('%20')#判断为空的时候加入非空的时候不加入
else:
ss.append(s[i])
i+=1
ss=''.join(ss)##把所有的都连在一起来
return ss

  

c++代码

#include<iostream>
using namespace std;
class Solution {
public:
void replaceSpace(char *str, int length) {
if (str == nullptr || length<0)
return;
int count = 0, i = 0;
while (str[i] != '\0')
{
if (str[i] == ' ')
{
count++;
}
i++;
}
int oldlen = i;
int newlen = i + count * 2;
if (newlen>length)
return;
while (oldlen != newlen)
{
if (str[oldlen] != ' ') {
str[newlen--] = str[oldlen];
}
else {
str[newlen--] = '0';
str[newlen--] = '2';
str[newlen--] = '%';
}
oldlen--;
}
return;
} };
int main(){
const int length = 100;
char str[length] = "We Are Happy";
Solution().replaceSpace(str, length);
cout << str << endl;
system("pause");
return 0;
}