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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With