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.

Code

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

// 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]);
System.out.println("...done!");
}
}

Output

Input String:
alpha|beta|gamma|delta
Splitting...
Number of tokens: 4
[0] alpha
[1] beta
[2] gamma
[3] delta
Third field: gamma
...done!

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.

Comments

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

Levi

Add new comment