Split Strings in Java

Before Java 1.4, StringTokenizer was used to split String in Java. After JDK 1.4, the use of StringTokenizer is discouraged, and instead the String.split(...) method or use of java.util.regex package is encouraged.

Steps

  1. Using StringTokenizer : The StringTokenizer is from the package java.util.StringTokenizer and the code snippet is as follows:

    StringTokenizer st =new StringTokenizer("string tokenizer example");
    System.out.println("tokens count: " + st.countTokens());
    // iterate through st object to get more tokens from it
    while (st.hasMoreElements()) {
    String token = st.nextElement().toString();
    System.out.println("token = " + token);
    }


    The result of the above code is
    tokens count: 3
    token = string
    token = tokenizer
    token = example
  2. Using split method: Java String class defines two split methods to split Java String object.
    (1) String[] split( String regEx) which splits the string according to given regular expression.
    (2) String[] split( String regEx, int limit ), which splits the string according to given regular expression. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array

    Code snippet for String[] split( String regEx)
    String str = "st1-st2-st3";
    String delimiter = "-";
    String[] temp;
    temp = str.split(delimiter);
    for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);


    The output is:
    st1
    st2
    st3

    Code snippet for String[] split( String regEx, int limit )
    String str = "st1-st2-st3";
    String delimiter = "-";
    String[] temp;
    temp = str.split(delimiter, 2);
    for(int i =0; i < temp.length ; i++)
    System.out.println(temp[i]);


    The output is
    st1
    st2-st3
  3. Using regular expression: An example for this is as follows

    String input = "st1:st2:st3";
    System.out.println(Arrays .asList(Pattern.compile(":").split(input)));
    System.out.println(Arrays.asList(Pattern.compile(":").split(input, 2)));
    Here, the second sysout is the example of the split method with the limit argument.

    The output of the above snippet is
    [st1, st2, st3]
    [st1, st2:st3]



Related Articles

  • Access a String's Length in Java Programming
  • Rename Variables in Eclipse (Java)
  • Name a Class in Java
  • Call a Method in Java