.substring 和空格,Java

.substring and whitespace, Java

我在 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.

所以,没有空格开始。

原因是子字符串将 return -8/-13 并且斜杠不是数字所以这将失败。在斜杠处拆分它,你就完成了。

int lastWhitespaceIndex = forecast.lastIndexOf(" ");
int lastSlashIndex = forecast.lastIndexOf("/");
int highs = Integer.parseInt(forecast.substring(lastWhitespaceIndex + 1, lastSlashIndex));

在我的测试中,这两种方法都失败了。如果您使用 Integer.parse(value),该值只能包含一个数字。如果不是 你得到 NumberFormatException.

public static int parseInt(String s) throws NumberFormatException Parses the string argument as a signed decimal integer. 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. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

Parameters:s - a String containing the int representation to be parsed

Returns:the integer value represented by the argument in decimal. Throws: NumberFormatException - if the string does not contain a parsable integer.