请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
来源:力扣(LeetCode)
方法一:python、java中replace函数
方法二:新建一个字符串,遍历原字符串找出空格后拼接“%20”到新字符串上
python:
class Solution:
def replaceSpace(self, s: str) -> str:
str1 = ''
for i in s:
if i == ' ':
str1+='%20'
else:
str1+=i
return str1
#或者
class Solution:
def replaceSpace(self, s: str) -> str:
return ''.join(char if char!=' ' else '%20' for char in s)
java:
class Solution {
public String replaceSpace(String s) {
String str1 = "";
for (int index = 0; index < s.length(); index++) {
if (s.charAt(index)==' ')
str1+="%20";
else
str1+=s.charAt(index);
}
return str1;
}
}
方法三:新建数组,逐一替换字符。
java
class Solution {
public String replaceSpace(String s) {
int len = s.length();
int arrLen = 0;
char[] arr = new char[len*3];
for (int index = 0; index < len; index++) {
if (s.charAt(index)==' ') {
arr[arrLen++]='%';
arr[arrLen++]='2';
arr[arrLen++]='0';
}
else
arr[arrLen++]=s.charAt(index);
}
return new String(arr,0,arrLen);
}
}
c:
char* replaceSpace(char* s){
int sumspace = 0,i=0,index=0;
for(i=0;s[i];i++)
if(s[i]==' ')
sumspace++;
char *str = (char*)malloc((strlen(s)+sumspace*2+1)*sizeof(char));
str[strlen(s)+sumspace*2]='\0';
for(i=0;s[i];i++)
if(s[i]==' '){
str[index++]='%';
str[index++]='2';
str[index++]='0';
}
else
str[index++]=s[i];
return str;
}
方法四:C++双指针从后往前判断替换。