【问题标题】:Concatenating String Arrays in For Loops with String conditions使用字符串条件连接 For 循环中的字符串数组
【发布时间】:2015-01-21 17:17:38
【问题描述】:

我目前正在运行一个 for 循环,该循环读取一个 List 对象,然后将它们拆分为数组。下面是示例代码:

List<String> lines = Arrays.asList("foo,foo,foo","bar,baz,foo","foo,baz,foo", "baz,baz,baz", "zab,baz,zab");
    for (String line : lines){
        String[] array = line.split(",");
        String[] arraySplit2 = array[0].split(",");
        System.out.print(Arrays.toString(arraySplit2));
    }

输出是:

[foo][bar][foo][baz][zab]

我希望在循环下将数组字符串连接成一个单独的字符串,以便它显示:

[foo, bar, foo, baz, zab]

我遇到了一些麻烦,因为循环条件阻止我执行增加 int i 技巧和使用System.arraycopy()。我对改变循环本身的结构等想法持开放态度。

【问题讨论】:

  • 要忽略重复项吗?

标签: java arrays loops for-loop concatenation


【解决方案1】:

您似乎试图从每行的第一个项目中创建一个数组。

首先,所以你需要先创建具有行数大小的结果数组:

String[] result = new String[lines.size()];
int index = 0;

您不需要第二次拆分,在 for 循环中填充结果数组:

   result[index++] = array[0]

之后循环打印你的结果数组。

【讨论】:

  • 当我使用这种方法时,似乎得到了以下代码for (String line : lines){ String[] array = line.split(","); String[] result = new String[lines.size()]; int index = 0; result[index++] = array[0]; System.out.print(Arrays.toString(result)); } 输出:[foo, null, null, null, null][bar, null, null, null, null][foo, null, null, null, null][baz, null, null, null, null][zab, null, null, null, null]
  • 在循环之前移动行 result = new... 和 index = 0。在循环之后移动打印。
【解决方案2】:

不是 100% 确定你想要什么,但我猜是这样的:

List<String> outList = new ArrayList<String>();
for (String line : lines) { 
    String[] array = line.split(",");
    outList.add(array[0]);
} 
String[] outStr = outList.toArray(new String[0]);
System.out.println(Arrays.toString(outStr));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 2015-08-02
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2014-08-02
    • 2022-06-27
    • 1970-01-01
    相关资源
    最近更新 更多