Java 循环从数组中拆分的字符串
我的程序当前扫描.txt文件内容并将其存储到数组中。现在,我需要在数组中分割字符串,而不需要将整个数组转换为一个长字符串。目前我有:Java 循环从数组中拆分的字符串,java,arrays,string,split,Java,Arrays,String,Split,我的程序当前扫描.txt文件内容并将其存储到数组中。现在,我需要在数组中分割字符串,而不需要将整个数组转换为一个长字符串。目前我有: List<String> content_lines = new ArrayList<String>(); while (scan.hasNextLine()) { content_lines.add(scan.nextLine()); } String
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 = string_array[i].split(":"+" ");
致:
现在的输出是:
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();
content\u split=string\u array[i]。拆分(“\\s*:\\s*”;
对于(int i=0;i将代码更改为:
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
}
String[]content\u split=新字符串[String\u array.length][];//创建二维数组
对于(int i=0;这是因为您正在覆盖它?content\u split=string\u array[i]。split(“:”+”)
我很高兴你找到了问题的解决方案。但是,实际的答案/解决方案不应该被编辑到你的问题中。一般来说,你应该通过提问来澄清问题,但不要在问题中包含答案。你应该用你用来解决问题的代码创建自己的答案,然后接受它(在接受您自己的答案之前,系统可能需要48小时的延迟)。当您自己解决了问题后,。这之前被回滚到rev#2,它本质上是删除问题并将答案放回原处,这没有多大意义。它也会使下面的答案无效,因此我将其移回rev#1。您需要在代码块和非代码块之间留一行空白。
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();
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
}