package practice;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Program {
public static void main(String args[]) throws Exception{
System.out.println("Enter the string");
String str=(new Scanner(System.in)).nextLine();
System.out.println(str);
String arr[]=str.split("+");
}
}
Asked
Active
Viewed 1,069 times
-1

Pshemo
- 122,468
- 25
- 185
- 269

Akshay Sharma
- 11
- 1
2 Answers
1
In Java, String's split
method expects a regex as an argument, and +
is a reserved character in regex syntax.
If you want to split
the string by +
character then you have to escape
it, e.g.:
String arr[] = str.split("\\+");
Here's javadoc on regex and patterns.

Darshan Mehta
- 30,102
- 11
- 68
- 102
1
You have to use \\+
because +
is a special character in regular expressions so you have to escape it :
String arr[] = str.split("\\+");
Instead of :
String arr[] = str.split("+");

Graham
- 7,431
- 18
- 59
- 84

Youcef LAIDANI
- 55,661
- 15
- 90
- 140
-
str.split("-"); is actually working. In this way "+" should also work. – Akshay Sharma Mar 18 '17 at 11:43
-
mines is not a special character in regex so you can use it like it is not like the + you ca learn more here to find understand what i mean http://users.cs.cf.ac.uk/Dave.Marshall/Internet/NEWS/regexp.html#info @AkshaySharma – Youcef LAIDANI Mar 18 '17 at 11:46
-
1@AkshaySharma "In this way "+" should also work" what makes you think so? Did you read documentation of `split` method (or duplicate question)? It mentions that `split` is using regex and `+` is one of regex special characters (along with `*`) while `-` is not (at least not in this case). If you want to use it as simple literal you need to escape it. – Pshemo Mar 18 '17 at 11:48