题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如,输入“We are happy.”,则输出“We%20are%20happy.”。
思路:准备两个指针P1和P2,P1指向原始字符串的末尾,P2指向替换之后的字符串的末尾,逐个把P1指定的字符移动到P2上
解决方案:
public class Question5 {
// length为字符数组string的总容量
public static void ReplaceBlank(char[] string, int length){
if (string == null || length <= 0) return;
// orignalLength为字符串string的实际长度
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while (string[i] != '\u0000'){
++originalLength;
if (string[i] == ' ') ++numberOfBlank;
++i;
}
// newLength为把空格替换为'%20'之后的长度
int newLength = originalLength + numberOfBlank * 2;
if (newLength > length) return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal){
if (string[indexOfOriginal] == ' '){
string[indexOfNew --] = '0';
string[indexOfNew --] = '2';
string[indexOfNew --] = '%';
}
else {
string[indexOfNew --] = string[indexOfOriginal];
}
--indexOfOriginal;
}
}
public static void main(String[] args) {
char[] string = new char[100];
char[] test = "Hello World".toCharArray();
System.arraycopy(test, 0, string, 0, test.length);
ReplaceBlank(string, 100);
System.out.println(new String(string).trim());
}
}