Bob the Bob
Bob the Bob

Reputation: 55

I cannot get the String split method to work properly

I am trying to split a String from an array into multiple Strings, before and after the "^". I used the String split method, but it is just storing the whole String in the first value of the array.

Output: b[0]= x^2 Expected: b[0] = x , b[1] = 2

Here is the code:

public class test {
    public static void main(String[] args) {   
        String a[] = {"x^2"};
        String b[] = a[0].split("^");

        System.out.println(b[0]);
    }
}

Upvotes: 2

Views: 50

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201537

Caret ^ is a special character in a regular expression meaning beginning of the String, escape it with \. Like,

String a[] = {"x^2"};
String b[] = a[0].split("\\^");

System.out.println(b[0]);

Upvotes: 4

Related Questions