import java.util.Arrays;
public class ReplaceBlank {
//替换空格,假设原始字符数组空间足够
public static void replaceBlank(char[] string, int length){
if (string == null || length <= 0)
return;
int originalCount = 0;
int blankCount = 0;
int newCount = 0;
//计数
int i =0;
while (string[i] != '\0'){
originalCount++;
if (string[i] == ' ')
blankCount++;
i++;
}
newCount = originalCount + blankCount * 2;
//检查内存是否足够
if (newCount > length)
return;
//替换
int indexOfOriginal = originalCount;
int indexOfNew = newCount;
while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal){
if (string[indexOfOriginal] != ' ')
string[indexOfNew--] = string[indexOfOriginal];
else{
string[indexOfNew--] = '0';
string[indexOfNew--] = '2';
string[indexOfNew--] = '%';
}
indexOfOriginal--;
}
}
//测试用例
public static void main(String[] args){
String str = "my name is zjp";
char[] string = Arrays.copyOf(str.toCharArray(), 100);
ReplaceBlank.replaceBlank(string, 100);
StringBuilder stringBuilder = new StringBuilder();
for (char c : string)
stringBuilder.append(c);
System.out.println(stringBuilder.toString());
}
}