题目描述:
请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例:
思路:
由于字符串不能通通过下表遍历,我们需要把字符串转换为字符数组再进行操作。
假设字符串全部是空格,那么替换后的长度为 3*s.length。
我们需要再创建一个长度为 3*s.length 的字符数组进行赋值与替换。最后只需把这个字符数组转换成字符串即可(注意字符数组是怎么转换成字符串的)。
实现代码:
class Solution {
public String replaceSpace(String s) {
char[] chars = new char[3 * s.length()];
char[] chars1 = s.toCharArray();
int index = 0;
for (int i = 0; i < chars1.length; i++) {
if (chars1[i]==' '){
chars[index++] = '%';
chars[index++] = '2';
chars[index++] = '0';
}else {
chars[index++] = chars1[i];
}
}
String newStr = new String(chars, 0, index);
return newStr;
}
}