Array index from related error when splitting string

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

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);
    }
}

      

+3


source to share


2 answers


.

is a special character in a regular expression. So when you use a method split()

, you need to avoid it.

Using



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

      

+6


source


So, like that. Dot is a regulator expression and when using a Reguler expression with a method, spilt()

it is split using a Reguler expression. You can get a more detailed idea of ​​this by checking out http://www.regular-expressions.info/dot.html .

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



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

      

will solve your problem.

+1


source







All Articles