问题
将一个字符串中的空格替换成“%20”,字符串替换操作在实际的工程有很重要的作用,有时候为了格式化或其他原因需要进行替换。
实现
思路:首先计算新的字符串的长度,然后从尾部进行替换;这样不会覆盖前面的数据。
/**
* 问题:将一个字符串中的空格替换为“%20”,假定字符串数组后面有足够的空间可以存放新增字符串,并且知道字符串的真实长度;
* 思路:从后往前进行转换,这样不必担心会覆盖前面的数据
* time:o(n)
* space:o(1)
*/
public static void replaceSpace(char[] str , int length){
int cnt = 0; // recode the number of space;
int len = 0; // recode the new array length;
int i;
for(i = 0 ; i < length; i++){
if(str[i] == ' '){
cnt ++;
}
}
// calculate the new array length;
len = length + cnt * 2;
str[len] = '\0';
// replace from the tail to head
for(i = length-1; i >= 0; i-- ){
if(str[i] == ' '){
str[len - 1] = '0';
str[len - 2] = '2';
str[len - 3] = '%';
len -= 3;
}else{
str[len-1] = str[i];
len --;
}
}
}