Splitting strings in Java

Java's split function packs a powerful punch. You can use it to split string on characters, symbols, substrings, a collection of symbols, or even regular expressions.

public class SplitString {

    public static void main(String[] args) {

        // splitting on a character
        String str = "splitstring";
        String[] t = str.split("t");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting on a substring
        str = "splitstring";
        t = str.split("tst");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting a digit
        str = "split4string";
        t = str.split("4");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting one special symbols
        str = "split$string";
        t = str.split("\\$");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting multiple special symbols
        str = "split$string#on@muliple%speical&symbols";
        t = str.split("[$#@%&]");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting with regular expressions
        str = "split9symbols";
        t = str.split("\\d");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();

        // splitting with regular expressions
        str = "regular9expression";
        t = str.split("[0-9]+");
        for (String i : t) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}

output

spli s ring 
spli ring 
split string 
split string 
split string on muliple speical symbols 
split symbols 
regular expression 
  • First part of the code splits the string on the character "t"
  • Second part splits on the substring "tst"
  • Third part splits on the number 4
  • Fourth part split on the dollar sign ($). Note the double backslash to escape the character. Similarly use \t for tabs and \n for newline characters.
  • Fifth part splits on $, #, @, %, and & symbols. Note the use of square brackets [] to make this possible.
  • Sixth part splits on any digit. \d is a regular expression abbreviation for "match any digit". Note the extra backslash to escape \d.
  • Last part also splits on any digit using a regular expression.
Technologies: