我的程序当前扫描.txt文件内容并将其存储到数组中。我现在需要在数组中拆分字符串而不将整个数组转换为一个长字符串。目前我有:
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数组会保持覆盖,并且只包含分割中的最后三个数据。
.txt文件包含如下数据:
Firstname Lastname
test1 : 1000 : 200
test2 : 1300 : 200
test3 : 1600 : 210
答案 0 :(得分:2)
将您的代码更改为:
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数组。
答案 1 :(得分:0)
更改此行:
content_split = string_array[i].split(":"+" ");
为:
content_split = string_array[i].split("\\s*:\\s*");
System.out.println(content_split[0] + " " + content_split[1] + " " + content_split[2]);//assuming you have 2 colons every line.
现在输出将是:
test1 1000 200
test2 1300 200
test3 1600 210
如果您不确定我可能拥有多少列,您可以执行以下操作:
content_split = string_array[i].split("\\s*:\\s*");
for(int i=0; i<content_split.length; i++)
System.out.print(content_split[i] + " ");
System.out.println();