题解 | #替换空格#
替换空格
http://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68
创建一个空字符数组,遍历原字符串,若是空格,依次添加'%'、'2'、'0';若不是空格,添加当前字符
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
public String replaceSpace (String s) {
// write code here
// 将String字符串拆分成char[]字符数组
int len_s = s.length();
char[] arrayChar = new char[len_s];
arrayChar = s.toCharArray();
// 计算有多少空格
int space_len = 0;
for(int i=0; i<arrayChar.length; i++){
if(arrayChar[i] == ' '){
space_len = space_len + 1;
}
}
char[] result_s = new char[len_s + 2 * space_len];
int index = 0;
for(int i=0; i<arrayChar.length; i++){
if(arrayChar[i] == ' '){
result_s[index] = '%';
result_s[index + 1] = '2'; // '20'不是字符,不能直接加入进去
result_s[index + 2] = '0';
index = index + 3;
}
else{
result_s[index] = arrayChar[i];
index = index + 1;
}
}
String re = new String(result_s);
return re;
}
}