题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
方法一:
public class Solution {
public String replaceSpace(StringBuffer str) {
if (str != null) {
String s = "%20";
for (int i = 0; i < str.length();) {
if (str.charAt(i) == ' ') {
str.insert(i, s);
str.deleteCharAt(i + 3);
i += 3;
} else {
i++;
}
}
} else {
return null;
}
return str.toString();
}
}
方法二:
public class Solution {
public String replaceSpace(StringBuffer str) {
String sti = str.toString();
char[] strChar = sti.toCharArray();
StringBuffer stb = new StringBuffer();
for(int i=0;i<strChar.length;i++){
if(strChar[i]==' '){
stb.append("%20");
}else{
stb.append(strChar[i]);
}
}
return stb.toString();
}
}
方法三:从后往前扫描
public class Test4 {
public static int replaceBlank(char[] string, int usedLength) {
if (string == null || string.length < usedLength) {
return -1;
}
int whiteCount = 0;
for (int i = 0; i < usedLength; i++) {
if (string[i] == ' ') {
whiteCount++;
}
}
int targetLength = whiteCount * 2 + usedLength;
int tmp = targetLength;
if (targetLength > string.length) {
return -1;
}
if (whiteCount == 0) {
return usedLength;
}
usedLength--;
targetLength--;
while (usedLength >= 0 && usedLength < targetLength) {
if (string[usedLength] == ' ') {
string[targetLength--] = '0';
string[targetLength--] = '2';
string[targetLength--] = '%';
} else {
string[targetLength--] = string[usedLength];
}
usedLength--;
}
return tmp;
}
public static void main(String[] args) {
char[] string = new char[50];
string[0] = ' ';
string[1] = 'e';
string[2] = ' ';
string[3] = ' ';
string[4] = 'r';
string[5] = 'e';
string[6] = ' ';
string[7] = ' ';
string[8] = 'a';
string[9] = ' ';
string[10] = 'p';
string[11] = ' ';
int length = replaceBlank(string, 12);
System.out.println(new String(string, 0, length));
}
}