-1

I'm trying to break up a string 192.168.1.2:6060;rport;branch=z9hG4bKNskFdtGO4".

I wanted to extract the port:ip before the first semicolon, and the branch number after the equal sign.

The code I tried was

temp = in.next();
System.out.println(temp.contains(";"));
System.out.println(temp.contains("="));
System.out.println("Temp: " + temp + " ");
sipName = temp.substring(0, temp.charAt(';'));
branch = temp.substring(temp.charAt('='));

I added the printlns to show if they characters were at least being found in the strings.

When I ran the code I get an StringIndexOutOfBoundsError at line sipName = temp.substring(0, temp.charAt(';'));

My console output is:

true
true
Temp: 192.168.1.2:6060;rport;branch=z9hG4bKb8NGxwdoR
Exception in thread "Thread-1" java.lang.StringIndexOutOfBoundsException: String index out of range: 59
...

It fails even if I just try System.out.println(temp.charAt(';'));

I'm not sure why this is happening. Is anyone able to explain? I'm stumped.

user1231232141214124
  • 1,339
  • 3
  • 16
  • 22

5 Answers5

3

Call temp.indexOf(';') instead of temp.charAt(';'). Similarly, call temp.indexOf('=') instead of temp.charAt('=').

indexOf tells you where the first occurrence of the given character is in the string. charAt returns a character code rather than a position within the string, so it doesn't make sense where you use it.

(And at any rate, when you call charAt you pass in a position within the string and not a character code. You could almost think of it as the opposite of indexOf.)

pobrelkey
  • 5,853
  • 20
  • 29
  • Thanks for the quick answer, it's been a while since I've had to use substring. Feel sort of silly now. I'll accept answer after the timer cool down. – user1231232141214124 Nov 28 '13 at 00:09
1

String.charAt takes an int. You are passing a char. Refer here for reference: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt%28int%29

dcp
  • 54,410
  • 22
  • 144
  • 164
1

Replace chatAt with indexOf.

This charAt is a logical mistake, you actually wanted indexOf.

OK, others were faster ;)

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
1
String sipName = StringUtils.substringBefore(str, ";");
String branch = StringUtils.substringAfter(str, "=");

StringUtils docs

Alex
  • 11,451
  • 6
  • 37
  • 52
1

What you need is

temp.indexOf(";");

You don't get any exceptions at compile time because it converts the ";" into its ASCII value which is 59. So it tries to access the 60th element of this string. Finally, this gives you a

StringIndexOutOfBoundsException

at runtime.

Artem Tsikiridis
  • 682
  • 6
  • 11