我在使用 Java 中的 .substring 方法时遇到了一个我不明白的错误。如果我有一个代表预测的字符串:
String forecast = "Sat, 7 Feb - Snow - -8/-13"
我可以通过调用来隔离温度数据
int lastWhitespaceIndex = forecast.lastIndexOf(" ");
int highs = Integer.parseInt(forecast.substring(lastWhitespaceIndex + 1));
但是,如果我将第二行更改为
int highs = Integer.parseInt(forecast.substring(lastWhitespaceIndex));
我的程序崩溃了。是否有一些我不知道的不允许字符串以空格开头的规则?
最佳答案
Integer.parseInt() 的文档明确指出:
The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
所以,开始时没有空格。
关于java - .substring 和空格,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359816/