Print array without brackets and commas

后端 未结 10 725
囚心锁ツ
囚心锁ツ 2020-11-29 23:28

I\'m porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits

相关标签:
10条回答
  • 2020-11-30 00:08

    You can use join method from android.text.TextUtils class like:

    TextUtils.join("",array);
    
    0 讨论(0)
  • 2020-11-30 00:09

    Replace the brackets and commas with empty space.

    String formattedString = myArrayList.toString()
        .replace(",", "")  //remove the commas
        .replace("[", "")  //remove the right bracket
        .replace("]", "")  //remove the left bracket
        .trim();           //remove trailing spaces from partially initialized arrays
    
    0 讨论(0)
  • 2020-11-30 00:10

    Basically, don't use ArrayList.toString() - build the string up for yourself. For example:

    StringBuilder builder = new StringBuilder();
    for (String value : publicArray) {
        builder.append(value);
    }
    String text = builder.toString();
    

    (Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)

    0 讨论(0)
  • 2020-11-30 00:15

    I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ",""); as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.

    0 讨论(0)
  • 2020-11-30 00:16

    If you use Java8 or above, you can use with stream() with native.

    publicArray.stream()
            .map(Object::toString)
            .collect(Collectors.joining(" "));
    

    References

    • Use Java 8 Language Features
    • JavaDoc StringJoiner
    • Joining Objects into a String with Java 8 Stream API
    0 讨论(0)
  • 2020-11-30 00:19

    the most simple solution for removing the brackets is,

    1.convert the arraylist into string with .toString() method.

    2.use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).

    3.Hurraaah..the result string is your string with removed brackets.

    hope this is useful...:-)

    0 讨论(0)
提交回复
热议问题