通过空格将字符串中的元素分隔成二维数组

时间:2016-09-01 19:20:32

标签: java arrays arraylist bufferedreader

我试图将文件中的以下字符串存储到二维数组中。我编写的代码除了当一个元素包含一个空格,它分成一个额外的元素时才有效。这是我的档案:

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]);

2 个答案:

答案 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:

  1. Determine the last index of a number in a line - and then everything up to that index "makes up the first column".
  2. The remainder of that line (after that last number) should go into the second column; only call trim() on that remaining string to get rid of the potentially leading spaces.

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);