简体   繁体   English

不带括号和逗号的打印数组

[英]Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems.我正在将 Hangman 游戏移植到 Android 并遇到了一些问题。 The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.最初的 Java 程序使用控制台,所以现在我必须以某种方式美化 output 以使其适合我的 Android 布局。

How do I print an array without the brackets and commas?如何打印没有括号和逗号的数组? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.该数组包含斜杠,并在猜出正确的字母时被一个接一个地替换。

I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ] .我正在使用 ArrayList class 的常用.toString() ArrayList和我的 output 格式如下: [ a, n, d, r, o, i, d ] I want it to simply print out the array as a single String .我希望它简单地将数组打印为单个String

I fill the array using this bit of code:我使用这段代码填充数组:

List<String> publicArray = new ArrayList<>();

for (int i = 0; i < secretWordLength; i++) {
    hiddenArray.add(secretWord.substring(i, i + 1));
    publicArray.add("-");
}

And I print it like this:我这样打印:

TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());

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

Basically, don't use ArrayList.toString() - build the string up for yourself.基本上,不要使用ArrayList.toString() - 为自己构建字符串。 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.) publicArray当它实际上不是一个数组时,我个人不会调用变量publicArray 。)

您可以使用android.text.TextUtils类中的join方法,例如:

TextUtils.join("",array);

first第一的

StringUtils.join(array, "");

second第二

Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")

EDIT编辑

probably the best one: Arrays.toString(arr)可能是最好的一个: Arrays.toString(arr)

With Java 8 or newer, you can use String.join , which provides the same functionality:对于 Java 8 或更新版本,您可以使用String.join ,它提供相同的功能:

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter返回由 CharSequence 元素的副本与指定分隔符的副本连接在一起的新字符串

String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"

With an array of a different type, one should convert it to a String array or to a char sequence Iterable:对于不同类型的数组,应该将其转换为 String 数组或 char 序列 Iterable:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };

//both of the following return "1234567"
String joinedNumbers = String.join("",
        Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
        Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));

The first argument to String.join is the delimiter, and can be changed accordingly. String.join的第一个参数是分隔符,可以相应地更改。

If you use Java8 or above, you can use with stream() with native.如果你使用 Java8 或更高版本,你可以使用 with stream() 和 native。

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

References参考

the most simple solution for removing the brackets is,删除括号的最简单的解决方案是,

1.convert the arraylist into string with .toString() method. 1. 使用 .toString() 方法将数组列表转换为字符串。

2.use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist). 2.使用String.substring(1,strLen-1).(其中strLen是从arraylist转换后的字符串长度)。

3.Hurraaah..the result string is your string with removed brackets. 3.Hurraaah..结果字符串是去掉括号的字符串。

hope this is useful...:-)希望这是有用的...:-)

I have used Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");我用过 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.正如我从上面的一些评论中看到的那样,但我还在逗号之后添加了一个额外的空格字符(部分.replace(", ","") ),因为当我在新行中打印出每个值时,仍然有空格字符在移动单词。 It solved my problem.它解决了我的问题。

I used join() function like:我使用了 join() 函数,如:

i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");

Which Prints:哪个打印:
HiHelloCheersGreetings


See more: Javascript Join - Use Join to Make an Array into a String in Javascript查看更多: Javascript Join - 在 Javascript 中使用 Join 将数组转换为字符串

String[] students = {"John", "Kelly", "Leah"};

System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));

//output: John, Kelly, Leah

您可以使用为 Java 8 及更高版本的流提供的 reduce 方法。请注意,您必须首先映射到字符串以允许在 reduce 运算符内进行连接。

publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();

I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution.我正在试验 ArrayList,我还想在打印 Output 后删除方括号,我找到了解决方案。 I just made a loop to print Array list and used the list method " myList.get(index) ", it works like a charm.我只是做了一个循环来打印数组列表并使用了列表方法“ myList.get(index) ”,它就像一个魅力。

Please refer to my Code & Output below:请参考我的代码 & Output 下面:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        ArrayList mylist = new ArrayList();
        Scanner scan = new Scanner(System.in);

        for(int i = 0; i < 5; i++) {
            System.out.println("Enter Value " + i + " to add: ");
            mylist.add(scan.nextLine());
        }
        System.out.println("=======================");

        for(int j = 0; j < 5; j++) {
            System.out.print(mylist.get(j));
        }
}
}

OUTPUT OUTPUT

Enter Value 0 to add:输入值 0 以添加:

1 1个

Enter Value 1 to add:输入值 1 以添加:

2 2个

Enter Value 2 to add:输入值 2 以添加:

3 3个

Enter Value 3 to add:输入值 3 以添加:

4 4个

Enter Value 4 to add:输入值 4 以添加:

5 5个

======================= =======================

12345 12345

只需使用您的数组初始化一个String对象

String s=new String(array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM