Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Index out of Bound Error when splitting a string

Tags:

java

Can someone please help me find the problem with the following code: it keeps giving me an:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

code

public class Hello{

    public static void main(String[] args){

        String tf = "192.168.40.1";
        String[] arggg = tf.split(".");
        String add = arggg[0];
        System.out.println(add);
    }
}
like image 295
Mike Avatar asked Feb 10 '23 13:02

Mike


2 Answers

. is a special charater in regex. So when using with split() method you need to escape it.

Use,

String[] arggg = tf.split("\\.");
like image 94
Codebender Avatar answered Feb 12 '23 05:02

Codebender


So here is the case. Dot is the Reguler Expression and when using Reguler expression with spilt() method it splitting using Reguler expression. You can get more detailed idea about it by following http://www.regular-expressions.info/dot.html link.

What you need to do is use escape charactor and tell split method you need to split using "."

String[] arggg = tf.split("\\.");

will solve your issue.

like image 25
Lasitha Benaragama Avatar answered Feb 12 '23 06:02

Lasitha Benaragama