Java ParseInt 健全性检查
我正在尝试从 String
数组元素解析 int
。这是我的代码:
String length = messageContents[k].replace("Content-Length:", "").replace(" ", "");
System.out.println("Length is: " + length);
int test= Integer.parseInt(length);
System.out.println
返回以下内容:长度为:23
但是,当我尝试将 String
解析为一个int
,一个java.lang.NumberFormatException
被抛出;
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
I'm trying to parse a int
from a String
array element. Here is my code:
String length = messageContents[k].replace("Content-Length:", "").replace(" ", "");
System.out.println("Length is: " + length);
int test= Integer.parseInt(length);
The System.out.println
returns the following: Length is: 23
However, when I try to parse the String
into an int
, a java.lang.NumberFormatException
gets thrown;
java.lang.NumberFormatException: For input string: "23"
I'm a bit confused how 23 wont get parsed into an int
. I can only assume that there is some other character in there that is preventing it, but I can't see it for the life of me.
Any suggestions?
Thanks
Update
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这个变体:
Try this variant:
该字符串中可能存在看不见的字符。
我的想法:使用带有模式/匹配器的正则表达式来删除字符串中的所有非数字,然后解析它。
There might be unseen characters in this string.
My idea: use a regex with a Pattern/Matcher to remove all the non-numerals in your string, then parse it.