循环从数组拆分字符串 [英] Looping a string split from an array

查看:91
本文介绍了循环从数组拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序当前扫描.txt文件的内容并将其存储到数组中。现在,我需要在数组内拆分字符串,而无需将整个数组转换为一个长字符串。当前我有:

My program currently scans a .txt files content and stores it into an array. I now need to split the string within the array without converting the whole array to one long string. Currently I have:

    List<String> content_lines = new ArrayList<String>();
    while (scan.hasNextLine()) 
        {
          content_lines.add(scan.nextLine());
        }

        String[] string_array = content_lines.toArray(new String[0]);

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

        /*The code is fine up until this point, this is where the split 
        occurs. Rather than storing each line that it has split, it 
        continues to overwrite the previous line.*/

        String[] content_split=null;
        for (int i=0; i<string_array.length; i++) 
        {
        content_split = string_array[i].split(":"+" ");

        }

代码可以很好地进行到拆分发生为止。它不会继续存储已拆分的每一行,而是会继续覆盖前一行。当我调试程序时,新的content_split数组将继续覆盖,并且仅包含拆分后的最后三段数据。

The code is fine up until the point where the split occurs. Rather than storing each line that it has split, it continues to overwrite the previous line. When I debug the program the new content_split array keeps overwriting and only contains that last three pieces of data from the split.

.txt文件包含如下数据:

The .txt file contains data like this:

          Firstname Lastname
          test1 : 1000 : 200
          test2 : 1300 : 200
          test3 : 1600 : 210


推荐答案

将代码更改为此:

String[][] content_split = new String[string_array.length][]; // create 2d array
for (int i=0; i<string_array.length; i++){
     content_split[i] = string_array[i].split(" : "); // store into array and split by different criteria
}

这将为您留下2D拆分内容的数组。

Which leaves you with a 2D array of your split content.

这篇关于循环从数组拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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