-1
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("+");

    }
}
Pshemo
  • 118,400
  • 24
  • 176
  • 257

2 Answers2

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
  • 28,982
  • 9
  • 60
  • 90
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,035
  • 17
  • 57
  • 82
YCF_L
  • 51,266
  • 13
  • 85
  • 129
  • 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 – YCF_L 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
  • aaaaahh ok i don't get thank you @Pshemo ;) – YCF_L Mar 18 '17 at 11:56