Java String split("|" ) method call not working correctly

java, split, string

Solution

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

Problem

``` 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?

Original source

Related problems