Splitting Strings in Java

One of the common string processing requirements in computer programs is to split a string into sub strings based on a delimiter. This can be easily achieved in Java using its rich String API. The split function in String class takes the delimiter as a parameter expressed in regular expression form.

The following Java program demonstrates the use of split function for splitting strings. Note that characters which has special meaning in regular expressions must be escaped using a slash (\) when passed as parameter to split function. Also note that an additional slash is required to escape slash in a Java string.

Please see this page on regular expressions for more details.

/**
 * Sample program to split strings in Java. The Java String API has a built-in 
 * split function which uses regular expressions for splitting strings.
 * 
 * 
 */
public class SplitString {
    
    public static void main(String[] args) {
        
        // Demo1 - splitting comma separated string
        String commaSeparatedCountries = "India,USA,Canada,Germany";
        String[]countries = commaSeparatedCountries.split(",");
        // print each country!
        for(int i=0;i<countries.length;i++) {
            System.out.println(countries[i]);
        }
        
        // Demo2 - Splitting a domain name into its subdomains
        // The character dot (.) has special meaning in regular expressions and 
        // hence must be escaped. Double slash is required to escape slash in Java 
        // string.
        String fullDomain = "www.blog.quickprogrammingtips.com";
        String[] domainParts = fullDomain.split("\\.");
        
        for(int i=0;i<domainParts.length;i++) {
            System.out.println(domainParts[i]);
        }
        
        
        // Demo3 - Splitting a string using regular expressions
        // In this example we want splitting on characters such as comma,dot or 
        // pipe. We use the bracket expression defined in regular expressions.
        // Only dot(.) requires escaping.
        String delimtedText = "data1,data2|data3.data4";
        String[] components = delimtedText.split("[,|\\.]");
        
        for(int i=0;i<components.length;i++) {
            System.out.println(components[i]);
        }   
    } 
}