6

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
Tony
  • 3,587
  • 8
  • 44
  • 77

2 Answers2

7

Try this variant:

int test= Integer.parseInt(length.trim());
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
3

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.

Silver Quettier
  • 2,045
  • 2
  • 26
  • 53
  • Normally I would. But this problem has got me very interested in finding out why the extra character, whatever it may be, isn't appearing within the System.Out. – Tony Jan 16 '12 at 13:37
  • 1
    It could be one of those non-printable control characters that you can only find by issuing `System.out.println(Arrays.toString(length.getBytes()));` – anubhava Jan 16 '12 at 13:40
  • [50, 51, 13] - I think 13 is a carriage return? – Tony Jan 16 '12 at 13:43
  • 1
    13 is indeed the carriage return / line feed or `\n` character. – anubhava Jan 16 '12 at 13:50