What are ways to split the string in Java?

Java String class provides a method to split the string using a delimiter. It takes delimiter as a regular expression and Splits this string around matches of the given regular expression.

This method has two overloaded versions.

public String[] split(String regex, int limit)

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

public String[] split(String regex)

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Examples:

String string = "+91-034556-345";
String[] parts = string.split("-");
if (parts.length == 3) {
	String part1 = parts[0]; // +91
	String part2 = parts[1]; // 034556
	String part3 = parts[2]; // 345
}

Note if using any special char in delimiter then we need to scape that char using backslash “\” with every char or Pattern.quote(“.”) method to scape entire string.

String string = "+91..034556..345";
String[] parts = string.split("\\.\\.");
if (parts.length == 3) {
	String part1 = parts[0]; // +91
	String part2 = parts[1]; // 034556
	String part3 = parts[2]; // 345
}

or

String string = "+91..034556..345";
String[] parts = string.split(Pattern.quote(".."));
if (parts.length == 3) {
	String part1 = parts[0]; // +91
	String part2 = parts[1]; // 034556
	String part3 = parts[2]; // 345
}

Use org.apache.commons.lang.StringUtils’ split method which can split strings based on the character or string you want to split.

Method signature:

public static String[] split(String str, char separatorChar);

You can use this as given below:

String str = "004-034556";
String split[] = StringUtils.split(str,"-");

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.