我从破解编码采访第五版关于更换空间的问题正在与%20
:用%替换空间时,长度值20
写一个方法,以取代所有空格用“字符串%20' 。您可能会认为字符串在字符串的末尾有足够的空间来容纳额外的字符,并且您将得到字符串的“真实”长度。 (注:如果用Java实现,请使用字符数组,这样就可以在地方执行此操作)
算法我是:
public static void replaceSpaces(String input, int length) {
char[] str = input.toCharArray();
int spaceCount = 0;
for(int i = length - 1; i >= 0; i--){
if(str[i] == ' ') {
spaceCount++;
}
}
int newLength = length + spaceCount * 2;
str[newLength] = '\0';
for(int i = length - 1; i >= 0; i--) {
if(str[i] == ' ') {
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
System.out.println(str);
} else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
System.out.println(str);
}
}
}
打印输出功能的每一步,这里是我的输出:
Mr John Smith h
Mr John Smith th
Mr John Smith ith
Mr John Smithmith
Mr John SmitSmith
Mr John S%20Smith
Mr John n%20Smith
Mr Johnhn%20Smith
Mr Johohn%20Smith
Mr JoJohn%20Smith
Mr%20John%20Smith
Mr%20John%20Smith
Mr%20John%20Smith
我有两个问题:
我们知道字符串的新长度是
17
。我不明白的是,为什么我们需要有[newLength - 1]
而不是[newLength]
。我们有兴趣替换当前的指数,不是吗?或者是因为新的长度是17,但是当转换为索引时,它实际上是16(第0个索引)。是什么目的:
str[newLength] = '\0';
在C中, “字符串” 是空终止。也许这个代码是一个过度直接的端口? – azurefrog
可以肯定的是:你知道你可以使用'String.replace(“”,“%20”);'相反,对吗? – Tom
@Tom这是一个面试问题 - 我希望我能在面试时这样做。 – theGreenCabbage