我创建了这个函数,它应该用字符串"%20"替换字符串中的所有空格。即:"约翰史密斯先生"成为" Mr%20John%20Smith"。为了实现这一点,我将字符串的所有字符放入一个数组并尝试循环,替换"的任何实例。 "用"%20"。出于某种原因,我写的代码似乎并没有认识到" "列表中的值,并跳过我循环的这一部分。因此,我没有获得替换了空格的新String,而是简单地返回相同的字符串,白色空格完好无损。有人可以帮助纠正我的错误吗?我通过Java Tutor运行它来可视化我的代码,它反映了同样的错误
import java.util.ArrayList;
public class Interview {
public static void main(String[] args) {
Interview theFunc = new Interview();
String d = "Mr John Smith ";
System.out.print(theFunc.URLify(d, 13));
}
public String URLify(String str, int x){
String result = "";
String real = str.substring(0,x);
String [] list = new String[real.length()];
int i = 0;
while (i != real.length()) {
list[i] = real.substring(i,i+1);
i = i +1;
}
int b = 0;
while (b < list.length) {
if (list[b] == " ") {
list[b] = "%20";
b = b + 1;
}else{
b = b + 1;
}
}
int d = 0;
while (d != list.length) {
result = result + list[d];
d =d + 1;
}
return result;
}
错误发生在第二个while循环中。谢谢!