gpt4 book ai didi

java - 写一个方法,用 '%20'替换字符串中的所有空格

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:25 24 4
gpt4 key购买 nike

我有一个关于 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,它正在剪切原始数组的最后一个字符。我一直在摸不着头脑,谁能向我解释为什么算法会这样做?

最佳答案

public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);

for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}

return sentence.toString();
}

关于java - 写一个方法,用 '%20'替换字符串中的所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10007631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com