Learn Everything about Java String Split Method

This is a simple tutorial for java beginners who are struggling on the String split() method. I have seen many students wondering about how to split the string in java with the help of split() method.
In this tutorial I am trying to show some simple exercises which can be used for learning and understanding String split and few other methods.

  1. Understanding the two flavors of split method
  2. Java.lang.String class contains two flavors of split() method, which can be used to split a string. Here are the javadoc definition of these two methods:
    public String[] split(String regex) - This method splits the string based on the given regular expression and returns array of strings.
    public String[] split(String regex,int limit) -  This method splits the string based on the given regular expression and returns array of strings. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
    So for example if you have a string ["This is a String"] then a) calling a split(" ") method (space as delimiter) on this string will convert it to an array of four strings [1] - This [2] - is [3] - a [4] - String a) calling a split(" ", 2) method on this string will convert it to an array of 2 strings [1] - This [2] - is a String
  3. Simplest thing first - Using the split() method with one character delimiter
  4. As you can see the split method supports regular expression therefore we should be able to use one or more chanracters as delimiter. To start with simple example I have chosen comma "," as a delimiter for my sentence. So for example if you have a string ["This,is,a,String"] then a split using comma as delimiter should result in array of four strings. See below example code.
    public static void  singleCharacterDelimiterTest() {
    String str = "This,is,a,String";
    String delimiter = ",";
    String[] splitStrings = str.split(delimiter);
    for (int i = 0; i < splitStrings.length; i++) {
    System.out.println(splitStrings[i]);
    }
    }
    
  5. How about using another string as a delimiter?
  6. Yes, you can always use a string as a delimiter. Remember that delimiter is a regular expression therefore any valid regular expression can be passed as a value in this parameter. So for example if you have a string ["ThisWORDisWORDaWORDString"] then a split using word [WORD] as delimiter is going result in array of four strings. See below example code.
    public static void  singleWordDelimiterTest() {
    String str = "ThisWORDisWORDaWORDString";
    String delimiter = "WORD";
    String[] splitStrings = str.split(delimiter);
    for (int i = 0; i < splitStrings.length; i++) {
    System.out.println(splitStrings[i]);
    }
    } 
    
    
    The output of this method will be
    [0] This
    [1] is
    [2] a
    [3] String
    
  7. How about using multiple characters as delimiter?
  8. There can be some scenarios where you may want to split the string based on multiple characters. So for example if you have a string ["This,is:a;String"] then a split using [comma or colon or semi-colon] as delimiter is required. You need not be an expert in Regular Expression to do this, just a simple use of pipe (|) operator should be sufficient to deal with this. so the regular expression for these 3 delimiter will be [",|:|;"] See below example code.
    public static void  multiCharacterDelimiterTest() {
    String str = "This,is:a;String";
    String delimiter = ",|:|;";
    String[] splitStrings = str.split(delimiter);
    for (int i = 0; i < splitStrings.length; i++) {
    System.out.println("[" + i + "] "+ splitStrings[i]);
    }
    }
    
    The output of this method will be
    [0] This
    [1] is
    [2] a
    [3] String
    
  9. How about using multiple words as delimiter?
  10. Lets assume a hypothetical scenario where you may want to split the string based on multiple words. So for example if you have a string ["ThisWORD1isWORD2aWORD3String"] then a split using [WORD1 or WORD2 or WORD3] as delimiter is required. Again the use of pipe (|) operator should be sufficient to deal with this. so the regular expression for these 3 delimiter will be ["WORD1|WORD2|WORD3"] See below example code.
    public static void  multiWordDelimiterTest() {
    String str = "ThisWORD1isWORD2aWORD3String";
    String delimiter = "WORD1|WORD2|WORD3";
    String[] splitStrings = str.split(delimiter);
    for (int i = 0; i < splitStrings.length; i++) {
    System.out.println("[" + i + "] "+ splitStrings[i]);
    }
    }
    
    The output of this method will be
    [0] This
    [1] is
    [2] a
    [3] String
    
  11. Keeping a watch on few special characters
  12. As we discussed in previous scenarios, the delimiter field is a regular expression and therefore there are few characters which have special meanings. If any such character needs to used as a delimiter then a escape sequence of \\ should be used in delimiter string. Some example characters are pipe (|) , dollar sign ($) , dot (.) carat (^) See below example code.
    public static void  specialCharaterDelimiterTest() {
    String str = "This|is^a$String";
    String delimiter = "\\||\\^|\\$";
    String[] splitStrings = str.split(delimiter);
    for (int i = 0; i < splitStrings.length; i++) {
    System.out.println("[" + i + "] "+ splitStrings[i]);
    }
    }
    
    The output of this method will be
    [0] This
    [1] is
    [2] a
    [3] String
    
    You can try many other regular expression and explore the power of this method. Visit http://www.regular-expressions.info/ to get more in-depth understanding on regular expressions.
  13. String Split using Java 1.1 Style - Using StringTokenizer class
StringTokenizer is a legacy class which is part of JDK since version 1.1. The String Tokenizer class allows an application to break a string into tokens. The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis. StringTokenizer's nextToken() method can be used to produce exact same output, See below example code.
public static void splitByTokenizer() {
StringTokenizer st = new StringTokenizer("This,is:a;String",",:;");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
The output of this method will be
This
is
a
String
The split() method has been introduced sice JDK version 1.4 and StringTokenizer use has been discouraged after that. Here is what Sun suggest in JDK 1.6 Javadocs "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead." Let me know your comments/feedback on this tutorial.
Playing with Java String Split method , Java String split, Java String splitting methods, Java String split functions, String split,play with String split java, splitting string in java exmaple, sample splitting in java, split in java,character split java word split java, all split java, split all spaces in java, split all spaces in string, split left spaces in string object, split right side spaces in java string, split all side spaces in java string, split inner spaces in java string, split in between spaces in java string, split comma, split pipe, split colon, split escape sequences, java string split function, split functions, java String split functions, Playing with Java String Split Function Basics, Playing with Java String Split method Basics, Playing with Java String Split Function fundamentals, Split using Java 1.1 Style - Using StringTokenizer class, programming course, programming tutorial, learn java string split function quickly, understand java string split function in detail, java string split in depth knowledge, string class method, string class function, string class manipulation, split string, how to split a string in java

Related

Tutorials 6791661008294189733

Post a Comment Default Comments

...

item