原文:
Write a method to replace all spaces in a string with ‘%20’.
译文:
写一个函数,把字符串中所有的空格替换为%20 。
先计算出空格个数,然后从后往前逐个替换空格,不用新开数组
package Arrays_Strings;
import CtCILibrary.AssortedMethods;
public class S1_4 {
// 先计算出空格个数,然后从后往前逐个替换空格
public static void replaceSpaces(char[] str, int length) {
int spaceCount = 0;
for(int i=0; i
=0; i--) {
if(str[i] == ' ') {
str[pos] = '0';
str[pos-1] = '2';
str[pos-2] = '%';
pos -= 3;
} else{
str[pos] = str[i];
pos--;
}
}
}
public static void main(String[] args) {
String str = "a s d";
char[] arr = new char[3*str.length()];
for (int i = 0; i < str.length(); i++) {
arr[i] = str.charAt(i);
}
replaceSpaces(arr, str.length());
System.out.println("\"" + AssortedMethods.charArrayToString(arr) + "\"");
}
}