如何从ArrayList中多余的空格 [英] How to remove extra spaces from arraylist

查看:392
本文介绍了如何从ArrayList中多余的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不从数据库中检索值,并将其添加到ArrayList中。这里是我的code ..

I have to retrieve values from database and add it into arraylist .Here is my code ..

 ArrayList country = new ArrayList();
 strQuery = "Select * from country";

        rs = conexiondb.Consulta(strQuery);

        while (rs.next()) {
            String toc = rs.getString("country");
            country.add(toc);
        }

        out.print(country);
        System.out.println(country);
        out.close();

我已经添加了从数据库中检索到country..and这里的所有值是在该国价值present ..

i have added all the values retrieved from database into country..and here is the values present in the country..

[亚太地区,北美,南美,欧洲]

现在根据我的需要,我有每个逗号值后删除空间,以便这样的..

Now as per my need i have to remove space after each comma values and make it like this..

[亚太地区,北美,南美,欧洲]

请你们帮我解决这个..

Please guys help me to solve this..

先谢谢了。

推荐答案

你们看到的是它的的ArrayList 格式的内容,你的查询没有结果,试一下像...

What you are seeing is how ArrayList formats it's contents, not the results of your query, try something like...

for (String name : country) {
    System.out.println("[" + name + "]");
}

要检查。如果仍然有空间在输出中,那么你可以使用字符串#修剪当你从数据库中提取的值,将它们放在面前的名单

To check. If there are still spaces in the output, then you can use String#trim when you extract the values from the database and before you place them in the List

如果您需要格式化字符串,您需要提供您自己的机制,例如...

If you need to format the String, you need to provide you own mechanism, for example...

List<String> values = new ArrayList<>();
values.add("APAC");
values.add("North America");
values.add("South America");
values.add("Europe");

System.out.println(values);

StringBuilder sb = new StringBuilder(128);
for (String value : values) {
    if (sb.length() > 0) {
        sb.append(",");
    }
    sb.append(value);
}
sb.insert(0, "[");
sb.append("]");

System.out.println(sb);

它输出...

[APAC, North America, South America, Europe]
[APAC,North America,South America,Europe]

这篇关于如何从ArrayList中多余的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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