string.split(\\ s +)无法处理前导空格[重复]

问题描述 投票:0回答:3

这个问题在这里已有答案:

我试图解析这个文件,以获得每行两个组件:

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.互联网上的所有结果只讨论拆分(\ s +)功能,但我找不到任何解决问题的方法我正面对。

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

coordinate[0]= coordinate[1]= 3000
java string bufferedreader
3个回答
1
投票

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

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

3
投票

看看你的输入

你的第一行工作正常,因为在行的开头没有空格。

但是在第2或第3行的情况下存在空的空间。

所以当你打电话

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

索引0将具有空格,索引1将具有值,即第二行中的0

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

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

0
投票

您也可以使用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));
}
© www.soinside.com 2019 - 2024. All rights reserved.