Split String by pipe(|) in java

Split String by pipe in java

In this post, we will see how to split String by pipe in java.

How to split String by pipe in java

There are multiple ways to split String by pipe (|) in Java.

Using split() method

You can use String’s split() method to split String by pipe in java.

Let’s say you want to read csv file delimited by pipe and store the data in String array. In this example, we will just simulate on header row.

Output:

[C, o, u, n, t, r, y, |, C, a, p, i, t, a, l, |, P, o, p, u, l, a, t, i, o, n]

Output does not look like what we were expecting. we were expecting a String array with three elements [Country, Capital , Population].

This happened because String's split() method takes regular expression as input and pipe is metacharacter in regex. In order to split String by pipe character, we need to escape pipe in split() method.

There are two ways to escape pipe character in split method.

Using \ to escape pipe

You can use \\ to escape pipe character. Let’s see with example:

Output:

[Country, Capital, Population]

As you can see, we got expected out now.

Using Pattern.quote() to escape pipe

You can also use Pattern’s quote() method to escape pipe character. Let’s see with example.

Output:

[Country, Capital, Population]

Using StringTokenizer

You can use StringTokenizer class to split String by pipe in java.

Here are steps to do it.

  • Create StringTokenizer object with constructor which takes String and delimiter as input.
  • Since we need to split String by |, we will pass delimiter as pipe.
  • Use while loop with hasMoreToken() method to check if there are more tokens available in String.
  • Use nextToken() method to get token based on delimiter.

Output:

[Country, Capital, Population]

Using Pattern class

You can also use combination of compile() and split() method of Pattern class to split String by pipe in java.

Here is an example:

Output:

[Country, Capital, Population]

Although this looks more complicated than String’s split() method.

That’s all about how to split String by pipe in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *