目前,代码应该用%20替换字符串中的所有空格。在大多数情况下,我认为逻辑在我调用的方法上是正确的,但是当我想看到返回的结果时,我的main方法没有打印任何东西 - 它为字符串打印一个空白。有人可以指示我将数组转换为字符串的逻辑错误吗?感谢您的时间和帮助。我附上了我的代码,以防你需要它。对不起,如果错误是愚蠢的。
public class replaceSpaces {
public static void main(String[] args) {
char[] data = checkfor20("yo o");
String text = String.valueOf(data); //turn char array into string representation
System.out.println(" new one: " + text);
}
private static char[] checkfor20(String string) {
int check = string.length(); //length of string
int spaceCount = 0, newLength; //count spaces and new length with %20 put in
char[] charstring = string.toCharArray(); // turn string into char array
for(int i = 0; i < check ; i++) { //get space count for newlenght
if (charstring[i] == ' ') {
spaceCount++;
}
}
newLength = check + (spaceCount * 2);
char[] newArray = new char[newLength];
for(int i = check - 1; i >= 0; i--) {
if(newArray[i] == ' ') { //get spaces and put it
newArray[newLength - 1 ] = '0';
newArray[newLength - 2 ] = '2';
newArray[newLength - 3 ] = '%';
newLength = newLength - 3;
}
else {
newArray[newLength - 1] = charstring[i];
newLength = newLength - 1;
}
}
return newArray; //return the new char array
}}
答案 0 :(得分:0)
为什么不newstring = oldstring.replace(" ","%20");
?
答案 1 :(得分:0)
为我的错误道歉我本来应该把我的阵列改成
if(charstring[i] == ' ')
而不是我创建的新数组。