我写了这个简单的程序,它在每个非数字字符处分割一个给定的输入。字符串分割错误的输出
public class Fileread {
public static void main(String[] args) throws IOException {
//Declarations
String[] temp;
String current;
//Execution
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
while ((current = br.readLine()) != null) {
temp = current.split("\\D"); //Splitting at Non Digits
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
}
}
}
这是input.txt中:
hello1world2
world3
end4of5world6
输出:
1
2
3
4
5
6
为什么那么多多余的空格出现?我需要在一个单独的行上打印每个数字,而没有间隔。我怎样才能解决这个问题?
使用'\\ d +'图案。但是,如果您的字符串以非数字开头,则仍然可以保留前导空元素。 –