6

我正在尝试intString数组元素中解析 a 。这是我的代码:

String length = messageContents[k].replace("Content-Length:", "").replace(" ", "");
System.out.println("Length is: " + length);
int test= Integer.parseInt(length);

System.out.println返回以下内容:长度为:23

但是,当我尝试将其解析Stringinta 时,java.lang.NumberFormatException会抛出 a ;

java.lang.NumberFormatException: For input string: "23"

我有点困惑如何 23 不会被解析为int. 我只能假设那里有其他角色在阻止它,但我一辈子都看不到它。

有什么建议么?

谢谢

更新

Despite the String length having only two characters, Java reports its length as three:
Length is: '23'
Length of length variable is: 3
length.getBytes = [B@126804e
4

2 回答 2

7

试试这个变种:

int test= Integer.parseInt(length.trim());
于 2012-01-16T13:38:46.990 回答
3

此字符串中可能有看不见的字符。

我的想法:使用带有模式/匹配器的正则表达式来删除字符串中的所有非数字,然后解析它。

于 2012-01-16T13:29:14.093 回答