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

发布于 2024-10-06 08:21:47 字数 688 浏览 2 评论 0原文

我正在将 Hangman 游戏移植到 Android,但遇到了一些问题。最初的 Java 程序使用控制台,所以现在我必须以某种方式美化输出,使其适合我的 Android 布局。

如何打印没有括号和逗号的数组?该数组包含斜杠,当猜到正确的字母时,该数组将被一一替换。

我使用的是 ArrayList 类的常用 .toString() 函数,我的输出格式如下:[ a, n, d, r, o, i ,d]。我希望它只是将数组打印为单个String

我使用这段代码填充数组:

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

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

我像这样打印它:

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

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 my Android layout.

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 ]. I want it to simply print out the array as a single 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());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

傾城如夢未必闌珊 2024-10-13 08:21:47

将括号和逗号替换为空格。

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

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
感情废物 2024-10-13 08:21:47

基本上,不要使用 ArrayList.toString() - 自己构建字符串。例如:(

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

顺便说一句,当变量 publicArray 实际上不是数组时,我个人不会调用它。)

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.)

二智少女 2024-10-13 08:21:47

对于 Android,您可以使用 < 中的 join 方法code>android.text.TextUtils 类如下:

TextUtils.join("",array);

For Android, you can use the join method from android.text.TextUtils class like:

TextUtils.join("",array);
鹿港小镇 2024-10-13 08:21:47

第一个

StringUtils.join(array, "");

第二个

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

编辑

可能是最好的:Arrays.toString(arr)

first

StringUtils.join(array, "");

second

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

EDIT

probably the best one: Arrays.toString(arr)

甩你一脸翔 2024-10-13 08:21:47

对于 Java 8 或更高版本,您可以使用 String.join,它提供相同的功能:

返回一个新的字符串,该字符串由 CharSequence 元素的副本与指定分隔符的副本连接在一起组成

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

对于不同类型的数组,应将其转换为 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()));

的第一个参数String.join 是分隔符,可以相应更改。

With Java 8 or newer, you can use String.join, which provides the same functionality:

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter

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:

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.

厌倦 2024-10-13 08:21:47

如果您使用Java8或更高版本,则可以与native一起使用stream()。

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

参考文献

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

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

References

雨后咖啡店 2024-10-13 08:21:47

删除括号的最简单的解决方案是,

  1. 使用 .toString() 方法将 arraylist 转换为字符串。

  2. 使用String.substring(1,strLen-1)。(其中strLen是数组列表转换后字符串的长度)。

  3. 结果字符串是去掉括号的字符串。

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. the result string is your string with removed brackets.

哭了丶谁疼 2024-10-13 08:21:47

我用过
Arrays.toString(array_name).replace("[","").replace("]","").replace(",","");
正如我从上面的一些评论中看到的那样,而且我还在逗号后面添加了一个额外的空格字符(.replace(", ","") 部分),因为当我打印时在新行中的每个值中,仍然有空格字符移动单词。它解决了我的问题。

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.

太傻旳人生 2024-10-13 08:21:47

我使用 join() 函数,例如:

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

Which Prints:
HiHelloCheersGreetings

查看更多: Javascript Join - 使用 Join 将数组转换为字符串在 JavaScript 中

I used join() function like:

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

差↓一点笑了 2024-10-13 08:21:47
String[] students = {"John", "Kelly", "Leah"};

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

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

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

//output: John, Kelly, Leah
庆幸我还是我 2024-10-13 08:21:47

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

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

You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.

publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
太阳哥哥 2024-10-13 08:21:47

我正在尝试 ArrayList,我还想在打印输出后删除方括号,我找到了一个解决方案。我刚刚做了一个循环来打印数组列表并使用列表方法“ myList.get(index) ”,它的工作原理就像一个魅力。

请参阅我的代码和输出如下:

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));
        }
}
}

输出

输入要添加的值 0:

1

输入要添加的值 1:

2

输入要添加的值 2:

3

输入要添加的值 3:

4

输入要添加的值 4:

5

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

12345

I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.

Please refer to my Code & Output below:

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

Enter Value 0 to add:

1

Enter Value 1 to add:

2

Enter Value 2 to add:

3

Enter Value 3 to add:

4

Enter Value 4 to add:

5

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

12345

苍暮颜 2024-10-13 08:21:47

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

String s=new String(array);

Just initialize a String object with your array

String s=new String(array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文