请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路: 遍历字符串,遇见“ 后替换成“%20”并把控制下标的变量加3,如果不是则继续,即控制下标的变量加1。
Java代码如下:
public class Solution {
public int Find(int start , char c,StringBuffer str){
int index = -1;
char[] ch = str.toString().toCharArray();
for ( int i = start ; i < str.length() ; i++){
if ( ch[i] == c){
index = i;
break;
}
}
return index;
}
public String replaceSpace(StringBuffer str) {
String s = "%20";
for ( int i = 0 ; i < str.length() ; ){
int index = Find(i, ' ', str);
if ( index != -1){
str.replace(index, index+1,s);
i = i + 3;
continue;
}else{
i++;
continue;
}
}
return str.toString();
}
}
C++代码如下:
class Solution {
public:
void replaceSpace(char *str,int length) {
int oldlength = 0;
int newlength = 0;
int i = 0;
//首先遍历数组计算新数组长度
while(str[i] != '\0'){
oldlength++;
if(str[i] == ' '){
newlength += 3;
}else{
newlength++;
}
i++;
}
//开始替换
while(oldlength >= 0){
if(str[oldlength] == ' '){
str[newlength--] = '0';
str[newlength--] = '2';
str[newlength--] = '%';
}else{
str[newlength--] = str[oldlength];
}
oldlength--;
}
}
};