【问题标题】:Printing String from a char array?从字符数组打印字符串?
【发布时间】:2015-06-06 00:21:18
【问题描述】:

目前代码应该用 %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 

}}

【问题讨论】:

    标签: arrays string char


    【解决方案1】:

    为什么不newstring = oldstring.replace(" ","%20");

    【讨论】:

      【解决方案2】:

      为我的错误道歉,我应该只是将我的数组更改为

      if(charstring[i] == ' ')
      

      而不是我创建的新数组。

      【讨论】:

        猜你喜欢
        • 2016-02-15
        • 2021-07-24
        • 1970-01-01
        • 2012-04-02
        • 2012-08-14
        • 2020-03-13
        • 2021-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多