替换空格
public class ReplaceSpace {
public static void main(String[] args) {
String string = "We are happy.";
char[] chars = string.toCharArray();
int count = 0; // 用于记录空格数
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' '){
count++;
}
}
char[] replaceChar = new char[chars.length + 2*count];
int index = chars.length - 1;
int replaceIndex = replaceChar.length - 1;
while(true){
if (index < 0 && replaceIndex < 0){
break;
}
if (chars[index] != ' '){
replaceChar[replaceIndex] = chars[index];
index--;
replaceIndex--;
}else if (chars[index] == ' '){
index--;
replaceChar[replaceIndex] = '0';
replaceChar[replaceIndex-1] = '2';
replaceChar[replaceIndex-2] = '%';
replaceIndex -= 3;
}
}
String result = "";
for (int i = 0; i < replaceChar.length; i++) {
result += replaceChar[i];
}
System.out.println(result);
}
}