我试图将文件中的以下字符串存储到二维数组中。我编写的代码除了当一个元素包含一个空格,它分成一个额外的元素时才有效。这是我的档案:
Student1 New York
Student 2 Miami
Student3 Chicago
所以我希望我的输出看起来像这样:
[Student1] [New York]
[Student 2] [Miami]
[Student3] [Chicago]
这是我的实际输出:
[Student1] [New] [York]
[Student] [2] [Miami]
[Student3] [Chicago]
这是我到目前为止所写的内容:
String file= "file.txt";
BufferedReader br = new BufferedReader(new FileReader(file));
while ((file = br.readLine()) != null) {
if (!file.isEmpty()) {
String strSingleSpace = file.trim().replaceAll("\\s+", " ");
String[] obj = strSingleSpace.trim().split("\\s+");
int i=0;
String[][] newString = new String[obj.length][];
for(String temp : obj){
newString[i++]=temp.trim().split("\\s+");
}
List<String[]> yourList = Arrays.asList(newString);
System.out.println(yourList.get(0)[0] + " " + yourList.get(1)[0]);
答案 0 :(得分:1)
Just giving you some "food for thought": your code is treating all lines the same way. As if they were looking exactly the same. Although you already made it very clear, that some lines have a different format.
In other words: there is no point in blindly splitting on spaces, if sometimes spaces belong into the first or the second column.
Instead:
You could put all of that into a single matching regular expression too; but as that is probably some kind of homework; I leave that exercise to the reader.
答案 1 :(得分:0)
我认为,对于您的特定测试用例,如果您更改此行,它将起作用:
String[] obj = strSingleSpace.trim().split("\\s+");\
到此:
String[] obj = strSingleSpace.trim().split("\\s+", 1);