将 ArrayList 输出到字符串而不出现 [,](括号) [英] Output ArrayList to String without [,] (brackets) appearing

查看:30
本文介绍了将 ArrayList 输出到字符串而不出现 [,](括号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个需要作为字符串返回的 ArrayList.现在我正在使用这种方法:

OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:

List<Customer> customers = new ArrayList<>();
List<Account> accounts = new ArrayList<>();


public String customerList() 
{
    String list = Arrays.toString(customers.toArray()); 
    return list;
}

public String accountList() 
{ 
    String account = Arrays.toString(accounts.toArray()); 
    return account;
}

这很好用,但问题是我在文本周围加了括号.我得到的东西如下:

This works fine, but the problem is that I get brackets around the text. I am getting stuff like:

 Customer list:
 --------------
 [Name: Last, First
 , Name: Last, First
 , Name: Last, First
 ]

当我想要这样的东西时:

When I want something like this:

 Customer list:
 --------------
 Name: Last, First
 Name: Last, First
 Name: Last, First

但是,与类似的问题不同,我不想简单地逐行输出.我需要将 ArrayList 存储在一个没有括号的字符串中,以便我可以使用它.

However, unlike similar questions, I don't simply want to output line by line. I need to store the ArrayList in a String without the brackets so I can work with it.

应该注意的是,我希望它看起来像的版本中的一个逗号是由不同类中的方法放置在那里的:

It should be noted that the one comma in the version I want it to look like was placed there by a method in a different class:

public final String getName()  
    { 
        return getLast() + ", " + getFirst(); 
    }

编辑 2: 通过调整我得到的两个答案,我找到了一个完整的解决方案.很难决定哪个是答案",因为我发现两者都很有用,但我选择了我可以更有选择地使用的那个.

EDIT 2: I was able to find a complete solution by adapting the two answers I was given. It was difficult deciding which was the "answer" because I found both useful, but went with the one that I could use more selectively.

public String customerList() 
{
    String list = Arrays.toString(customers.toArray()).replace(", N", "N").replace(", N", "N");
    return list.substring(1,list.length()-1);
}

为了删除括号,我使用了修改后的返回值.删除逗号需要我关注这样一个事实,即每一行都以N"开头,但这种方法的缺陷是,如果我在那里更改它,如果我忘记在此处更改它,代码就会中断.尽管如此,它还是解决了我的具体问题,我可以随时根据需要在这两个地方给自己做笔记.

To remove the brackets I used the modified return. Removing the comma required me to focus on the fact that each line will start with an "N", but the flaw in this approach is that the code would break if I forget to change it here if I change it there. Still, it solves my specific problem, and I can always notate to myself in both places as needed.

推荐答案

您可以尝试用空格替换 '[' 和 ']'

You could try to replace the '[' and ']' with empty space

String list = Arrays.toString(customers.toArray()).replace("[", "").replace("]", "");

这篇关于将 ArrayList 输出到字符串而不出现 [,](括号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆