【发布时间】:2012-04-17 22:55:26
【问题描述】:
我有一个关于编程问题的问题,来自 Gayl Laakmann McDowell 的《Cracking The Code Interview》,第 5 版。
问题说明:编写一个方法,用 '%20' 替换字符串中的所有空格。假设字符串在字符串末尾有足够的空间来容纳额外的字符,并且你得到了一个字符串的真实长度。我使用了书籍代码,使用字符数组在 Java 中实现了解决方案(鉴于 Java 字符串是不可变的):
public class Test {
public void replaceSpaces(char[] str, int length) {
int spaceCount = 0, newLength = 0, i = 0;
for(i = 0; i < length; i++) {
if (str[i] == ' ')
spaceCount++;
}
newLength = length + (spaceCount * 2);
str[newLength] = '\0';
for(i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
}
else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
System.out.println(str);
}
public static void main(String[] args) {
Test tst = new Test();
char[] ch = {'t', 'h', 'e', ' ', 'd', 'o', 'g', ' ', ' ', ' ', ' ', ' ', ' '};
int length = 6;
tst.replaceSpaces(ch, length);
}
}
我从replaceSpaces() 调用中得到的输出是:the%20do,它正在切割原始数组的最后一个字符。我一直在为此摸不着头脑,谁能向我解释一下为什么算法会这样做?
【问题讨论】:
-
您没有使用
String#replace和String#replaceAll方法的任何特殊原因? -
Java 字符串没有
\0。另外,当您检测到空格时,您覆盖的字符会发生什么情况? -
这是本书作者实现的代码。是不是错了??
-
我以为 str[newLength] = '\0';应该给你索引超出范围错误之类的......???