Question

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
Was it helpful?

Solution

Try this variant:

int test= Integer.parseInt(length.trim());

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top