1

i want to split a string which contains +, i m using split() on String object as: but it shows exception.

class StringTest 
{
    public static void main(String[] args) 
    {
        String val= "004+0345564";
        String arr[]=val.split("+");
        for(int i=0;i<=arr.length-1;i++){
            System.out.println(arr[i]);
        }
    }
}
0

7 Answers 7

6

String.split takes a regular expression as its argument. A + in a regular expression has a special meaning. (One or more of previous).

If you want a literal +, you need to escape it using \\+. (The regular expression grammar is \+ but you need to escape the backslash itself in Java using a second backslash).

Sign up to request clarification or add additional context in comments.

Comments

3
String arr[] = val.split("\\+");

instead of

String arr[]=val.split("+");

Comments

1

try this

class StringTest 
{
    public static void main(String[] args) 
    {
        String val= "004+0345564";
        String arr[]=val.split("\\+");
        for(int i=0;i<=arr.length-1;i++){
            System.out.println(arr[i]);
        }
    }
}

Comments

1

Split takes regex. You need to escape +

String arr[]=val.split("\\+")

Comments

1
String arr[] = val.split("\\+");

Comments

1

You need to use

    String arr[] = val.split("\\+");

Instead of

    String arr[]=val.split("+");

The split method takes regex as inputs. You can also refer String#split to confirm the same.

Comments

0

Actual syntax is

public String[] split(String regex, int limit)

//or

public String[] split(String regex)

So use, below one.

String arr[] = val.split("\\+",0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.