【问题标题】:Converting a string[] into a string then split into an array将 string[] 转换为字符串,然后拆分为数组
【发布时间】:2017-11-16 13:38:22
【问题描述】:

我需要帮助创建一个拆分字符串的循环。到目前为止,我有下面的代码。

    System.out.println("*FILE HAS BEEN LOCATED*");
    System.out.println("*File contains: \n");
    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine()) 
    {
      lines.add(scan.nextLine());
    }

    String[] arr = lines.toArray(new String[0]);

    String str_array = Arrays.toString(arr);

    String[] arraysplit;
    arraysplit = str_array.split(":");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arr[i].trim();
        System.out.println(arr[i]);
    }

其中一个字符串的示例是

        Firstname : Lastname : age 

我希望它将字符串拆分为另一个数组,如下所示:

        Firstname
        Lastname
        age

我在运行代码时仍然遇到错误,好像当我将数组转换为字符串时,它会在字符串中放入逗号,因此在我尝试将字符串拆分时会导致问题 : not ,

图片:

【问题讨论】:

  • 还有什么问题?
  • 会不会是你把事情弄得太复杂了? "Firstname : Lastname : age".split("\\s*:\\s*") 应该会给你想要的结果。
  • 这个问题仍然毫无意义。 You 调用Arrays.toString(arr),它使用, 作为分隔符清楚且明显地将每个数组项写入一个字符串,但您希望它的行为不像它那样记录在案。为什么?

标签: java arrays string list split


【解决方案1】:

问题:您正在使用旧数组 arr 来显示值,而 arraysplit 将得到 split 方法的结果值,因此您需要在 arraysplit 上应用 trim()' s 元素并将元素分配回相同的索引

String[] arraysplit;
arraysplit = str_array.split(":");

for (int i=0; i<arraysplit.length; i++)
{
    arraysplit[i] = arraysplit[i].trim();
    //              ^^^^^^^^^^^^ has values with spaces
    System.out.println(arr[i]);
}

System.out.println(arraysplit[i]);

为了简化解决方案(列表到数组和数组到字符串的复杂化)

1.) 创建长度为sizeOfList * 3的数组

2.) split 使用\\s*:\\s* 的列表元素

3.) 使用带有j作为结果数组索引的数组副本来跟踪数组索引

    String result[] = new String [lines.size()*3];
    int j=0;
    for (int i=0; i<lines.size(); i++)
    {
        System.arraycopy(lines.get(0).split("\\s*:\\s*"), 0, result, j, 3);
        j+=3;
    }
    System.out.println(Arrays.toString(result));

你可以在哪里使用regexstr_array.split("\\s*:\\s*");

\\s*:\\s* : \\s* 表示零个或多个空格,然后是 : 字符,然后是零个或多个空格

arraysplit = str_array.split("\\s*:\\s*");
// just use values of arraysplit

【讨论】:

  • 请看我附加到我的问题的图像,因为我在运行代码时仍然遇到错误,好像当我将数组转换为字符串时,它在字符串中放置了逗号因此它会导致问题,因为我试图将字符串拆分为 : not ,
  • @rxbert 您的输入是否有可能包含字母和数字以外的任何特殊字符?如果没有,那么简单的方法是arraysplit = str_array.split("\\s*\\W\\s*");
【解决方案2】:

使用这个正则表达式\s*:\s*分割

String[] arraysplit = str_array.split("\\s*:\\s*");

详情:

  • \s* 零个或多个空格
  • 后跟横向字符:
  • 后跟\s* 零个或多个空格

regex demo

【讨论】:

  • 请看我附加到我的问题的图像,因为我在运行代码时仍然遇到错误,好像当我将数组转换为字符串时,它在字符串中放置了逗号因此它会导致问题,因为我试图将字符串拆分为 : not ,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
相关资源
最近更新 更多