Splitting a Java String by the pipe symbol using split("|")

Splitting a Java String by the pipe symbol using split("|")

To split a Java string by the pipe symbol | using the split() method, you need to escape the pipe symbol because it is a special character in regular expressions. You can escape it by using two backslashes \\| as the delimiter. Here's how you can do it:

public class Main { public static void main(String[] args) { String inputString = "apple|banana|cherry|date"; // Split the string by the pipe symbol String[] parts = inputString.split("\\|"); // Print the split parts for (String part : parts) { System.out.println(part); } } } 

In the code above, we use inputString.split("\\|") to split the inputString by the pipe symbol. Since split() expects a regular expression as its argument, we need to escape the pipe symbol with double backslashes, resulting in "\\|". This way, the string will be correctly split into an array of parts:

apple banana cherry date 

So, by escaping the pipe symbol as \\|, you can split a Java string using the split() method.


More Tags

azure-application-gateway android-8.0-oreo android-gridlayout windows-installer x11 timeout httpcontext clipboard.js plugins angular-reactive-forms

More Java Questions

More Geometry Calculators

More Livestock Calculators

More Chemical reactions Calculators

More Animal pregnancy Calculators