Splitting tokens from delimited string in Java

Need to get a particular field from a pipe delimited string in Java?

Say you have a string like "alpha|beta|gamma|delta" and want the third token. Here is how you do it in Java.


public class StringSplit {
public static void main(String[] args) {
String inputString = "alpha|beta|gamma|delta";
System.out.println("Input String: \n" + inputString);

// Here is the core - replace the regex with
// whatever delimiter you have. Since '|' is
// a special character in regular expression,
// we need to escape it.
String tokens[] = inputString.split("\\|");

int numTokens = tokens.length;
System.out.println("Number of tokens: " + numTokens);

for (int i = 0; i System.out.println("[" + i + "] " + tokens[i]);

// 3rd field?
System.out.println("Third field: " + tokens[2]);


Input String:
Number of tokens: 4
[0] alpha
[1] beta
[2] gamma
[3] delta
Third field: gamma

The delimiter in this example is the pipe (|) character. It can be any character or set of characters - just pass it to the String.split() method as a regular expression.


Hello There,

I am Levi from UK, I am doing my Honours degree in Teesside University I was doing research in delimiter.

I found your website which was very useful to me .

Many Thanks


Add new comment