Yogesh
Yogesh

Reputation: 37

split() method on string not working

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

Upvotes: 1

Views: 108

Answers (7)

Balwinder Singh
Balwinder Singh

Reputation: 2282

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.

Upvotes: 1

Umesh Patil
Umesh Patil

Reputation: 10685

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

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

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).

Upvotes: 6

Kanaiya Katarmal
Kanaiya Katarmal

Reputation: 6108

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

Upvotes: 1

Deepu--Java
Deepu--Java

Reputation: 3820

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

Upvotes: 1

newuser
newuser

Reputation: 8466

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

instead of

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

Upvotes: 3

sanbhat
sanbhat

Reputation: 17622

Split takes regex. You need to escape +

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

Upvotes: 1

Related Questions