【问题标题】:string.split(\\s+) unable to deal with leading spaces [duplicate]string.split(\\s+) 无法处理前导空格 [重复]
【发布时间】:2018-09-19 04:21:48
【问题描述】:

我正在尝试解析此文件以获取每行两个组件:

10000      0
    0  10000
 3000   7000
 7000   3000
20000  21000
 3000   4000
14000  15000
 6000   7000

我用来扫描和拆分内容的代码是:

BufferedReader br = new BufferedReader(new FileReader(file));

while ((st = br.readLine()) != null){
            String[] coordinates = st.split("\\s+");
            System.out.println("coordinate[0]= " + coordinates[0] + "coordinate[1]= "+ coordinates[1]);
        }

我没有得到第二行“0 10000”的预期结果,我得到:

coordinate[0]= coordinate[1]= 0

谁能帮我解决这个问题,所以我得到坐标[0]= 0,坐标[1]= 10000。互联网上的所有结果都只讨论 split(\s+) 函数,但我找不到任何解决了我面临的问题。

即使是第三行的结果也不正确(开头有一个空格)。

coordinate[0]= coordinate[1]= 3000

【问题讨论】:

标签: java string bufferedreader


【解决方案1】:

查看您的输入

您的第一行工作正常,因为行首没有空格。

但在第 2 行或第 3 行的情况下,存在空格。

所以当你打电话时

st.split("\\s+");

索引 0 将有空格,索引 1 将在第 2 行具有值 ie 0

要解决此问题,您可以在拆分此类内容之前删除空格

String[] coordinates = st.trim().split("\\s+");

【讨论】:

    【解决方案2】:

    一种选择是在拆分之前修剪整个字符串。

    String[] coordinates = st.trim().split("\\s+");
    

    【讨论】:

      【解决方案3】:

      你也可以使用regex来解决这个问题

      (\d+)\s+(\d+)
      

      代码如下:

      //read file into a string
      String content = new String(Files.readAllBytes(Paths.get(file)), "UTF-8");
      
      //create regex and pattern
      Pattern pattern = Pattern.compile("(\\d+)\\s+(\\d+)");
      Matcher matcher = pattern.matcher(str);
      
      //output results
      while (matcher.find()) {
          System.out.print("coordinate[0]= " + matcher.group(1));
          System.out.println("coordinate[1]= " + matcher.group(2));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-27
        • 2021-11-29
        • 1970-01-01
        • 1970-01-01
        • 2014-11-12
        相关资源
        最近更新 更多