Java ParseInt Security Check

I am trying to parse an int from an element of a String array. Here is my code:

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

System.out.println returns the following: Length: 23

However, when I try to parse String to int , a java.lang.NumberFormatException gets thrown;

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

I am a bit confused as 23 is not parsed in int . I can only assume that there is some other character that prevents him, but I do not see him for life.

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 
+6
source share
2 answers

Try this option:

 int test= Integer.parseInt(length.trim()); 
+7
source

This line may contain invisible characters.

My idea: use the regex with the / Matcher pattern to remove all nonzero digits in your string, then parse it.

+3
source

Source: https://habr.com/ru/post/906098/


All Articles