[英]How can I remove white spaces from an input?
This is the input: enter image description here这是输入:在此处输入图像描述
I want to get the last number but how?我想得到最后一个数字,但是如何呢? (1,2,6)
(1,2,6)
I tried this:我试过这个:
String line = scanner.nextLine();字符串 line = scanner.nextLine();
String[] parts = line.split(" "); String[] parts = line.split(" ");
int ProductCount =Integer.parseInt(parts[3].replaceAll(" ", "")); int ProductCount =Integer.parseInt(零件[3].replaceAll(" ", ""));
If you want the last number you can do it like this.如果你想要最后一个数字,你可以这样做。
.*?
reluctantly grab the characters(\\d+)$
- capture one or more digits at end of string. (\\d+)$
- 在字符串末尾捕获一位或多位数字。$1
back reference to captured value (21 in this case) $1
对捕获值的反向引用(在本例中为 21)String s = "kssk sk k22 s 21";
int v = Integer.parseInt(s.replaceAll(".*?(\\d+)$","$1"));
System.out.println(v);
prints印刷
21
A somewhat better alternative might be to do the following if there is always a space before the last number.如果最后一个数字之前始终有一个空格,则更好的替代方法可能是执行以下操作。
int i = s.lastIndexOf(' '); // returns -1 if no space is found.
int v = Integer.parseInt(s.substring(i+1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.