14
public class SplitStr {

    public static void main(String []args) {
        String str1 = "This | is | My | Account | For | Java|";
        String str2 = "This / is / My / Account / For / Java/";
       // String[] arr = str.split("|");

        for(String item : str1.split("|")) {
            System.out.print(item);
        }
    }
}

The program is working correctly with String str2 but it is not working with String str1 What are the possible flows in this program?

user2677600
  • 153
  • 1
  • 2
  • 11

3 Answers3

53

String#split() expects a regular expression as the first argument and | is a control character in regex.

To make regex parser understand that you mean to split by the literal |, you need to pass \| to the regex parser. But \ is a control character in Java string literals. So, to make Java compiler understand that you want to pass \| to the regex parser, you need to pass "\\|" to the String#split() method.

Jae Heon Lee
  • 1,101
  • 6
  • 10
23

Use

str1.split("\\|")

instead of

str1.split("|")

You need to escape |

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
10

split expects a regular expression, and since | is a special character in regular expressions, you have to escape it. Try str.split("\\|"). Example:

>>> Arrays.asList("This | is | My | Account | For | Java|".split("\\|"));
[This ,  is ,  My ,  Account ,  For ,  Java]
tobias_k
  • 81,265
  • 12
  • 120
  • 179