我在文本文件中有以下文字: AAA:A,B,C BBB:d,F
如何创建数组列表,其中每个数组仅包含“:”之后的单词且不包含逗号 例如,array1将是:[a b c] array2将是[d f]
到目前为止我有这个代码,但我得到了输出: [aaa:a,b,c] [BBB:d中,f]
// this list will store all the created arrays
List<String[]> arrays = new ArrayList<String[]>();
// use a BufferedReader to get the handy readLine() function
BufferedReader reader = new BufferedReader(new FileReader("scor.txt"));
for (String line1 = reader.readLine(); line1 != null;
line1 = reader.readLine()) {
String[] floatStrings = line1.split(",");
String[] textline = new String[floatStrings.length];
for (int i = 0; i < textline.length; ++i) {
textline[i] = floatStrings[i];
}
arrays.add(textline);
}
for (String[] arr : arrays) {
System.out.println(Arrays.toString(arr));
}
}
我稍微更改了代码:
String[] textline = new String[floatStrings.length-1];
for (int i = 0; i < textline.length; ++i) {
String[] newTextlineWithoutFirst = Arrays.copyOfRange(floatStrings, 1, floatStrings.length);
textline[i] = newTextlineWithoutFirst[i];
}
arrays.add(textline);
}
for (String[] arr : arrays) {
System.out.println(Arrays.toString(arr));
}
}
答案 0 :(得分:1)
首先尝试拆分:
,然后在[1]
上拆分,
...
for (String line1 = reader.readLine(); line1 != null; line1 = reader.readLine()) {
String[] splitString = line1.split(":");
splitString = splitString[1].split(",");
String[] textline = new String[splitString.length];
for (int i = 0; i < textline.length; ++i) {
textline[i] = splitString[i];
}
arrays.add(textline);
}