我想从一行中提取字符串

时间:2018-07-01 05:59:48

标签: java arrays string

以下内容在文本文件中可用。我想提取数据(姓名,年龄,工作经验,职位)。我能怎么做?我尝试使用java stringtokenizer和split函数提取数据。但是无法提取数据。

Name                                     Age                   Working Experience          Position                     
John                                     23                    10                          Team Leader                          
Christian Elverdam                       27                    7                           Director                    
Niels Bye Nielsen                        59                    16                          Composer
Rajkumar Hirani                          40                    23                          Director               
Vidhu Vinod Chopra                      58                    21                          Screenplay

预期产量:

John              |23|10|Team Leader|
Christian Elverdam|27|7 |Director   |
Niels Bye Nielsen |59|16|Composer   |
Rajkumar Hirani   |40|23|Director   |
Vidhu Vinod Chopra|58|21|Screenplay |

1 个答案:

答案 0 :(得分:0)

请勿使用StringTokenizer

  

StringTokenizer是一个遗留类,出于兼容性原因保留,尽管在新代码中不鼓励使用它。建议寻求该功能的任何人都使用split的{​​{1}}方法或String软件包。

如果您在两个或多个空格上分开,可以使用split()java.util.regex

演示

split(" {2,}")

输出

String input = "Name                                     Age                   Working Experience          Position                     \n" +
               "John                                     23                    10                          Team Leader                          \n" +
               "Christian Elverdam                       27                    7                           Director                    \n" +
               "Niels Bye Nielsen                        59                    16                          Composer\n" +
               "Rajkumar Hirani                          40                    23                          Director               \n" +
               "Vidhu Vinod Chopra                      58                    21                          Screenplay\n";

List<String[]> rows = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new StringReader(input))) {
    in.readLine(); // skip header line
    for (String line; (line = in.readLine()) != null; ) {
        rows.add(line.split(" {2,}"));
    }
}
for (String[] row : rows)
    System.out.println(Arrays.toString(row));