Reputation: 37
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
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
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
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
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
Reputation: 8466
String arr[] = val.split("\\+");
instead of
String arr[]=val.split("+");
Upvotes: 3
Reputation: 17622
Split takes regex. You need to escape +
String arr[]=val.split("\\+")
Upvotes: 1