How to Use Java String Class split() Method

String split() Method

Function Description

This Java String Class method is used to break the string around all the matches of the specified regular expression and returns an Array. The array returned by this string contains each substring of the string that is broken by the sequence of characters matched to the specified regular expression. All broken substrings of this Array are stored in the order they occur in the string. If the regular expression does not match any part of the string to be split, then its resulting array contains only one element, namely this string.

In String class, split is defined as an overloaded method

  1. One method is to break the string around all the matches of the specified regular expression

  2. Another method is to break the string around all the matches of the specified regular expression in the specified limit. The specified regular expression will be applied from the beginning of the string up to the specified limit. A specified limit is a maximum limit to break the string.

This method excludes the matching sequence of character(s) specified by the regular expression from the broken substring in the Array.

For Example: We are breaking the “Welcome to String split() function learning”, if it has matching characters ”sp”.

“Welcome to String split() function learning”.split(“sp”) . This statement will return an Array of size #2

Output substrings in this Array will be:

  • Welcome to String

  • lit() function learning (Notice- ‘sp’ is excluded)

When a sequence of character(s)  specified by regular expression, matches at the beginning of the string, then an empty substring is included at the beginning of the returned array.

For Example: If we break the string “” at matching expression”W” then it will return an array of size #2 in which first value of array will be empty

“Welcome to String split() function learning”.split(“W”) will return Array of size 2

Output substrings in this Array will be:

  • “Blank” (Array first value)

  • elcome to String split() function learning” (Array second value)

If specified regular expression is not valid, it throws PatternSyntaxException

If specified regular expression is null, it throws NullPointerException

 If the specified limit is zero or less than zero, then limit value will not be considered and it will break the string around all the matches substring specified in the regular expression.

Method Signature

  1. Method to break the string from all the matches substring specified by the regular expression.

    public String[] split(String regex)

  2. Method to break the string from all the matches substring specified by regular expression in the specified limit.

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

Parameters

regex: Regular expression to be match and break the string

limit: int type value to limit the string termination. It is a maximum number to split the string.

Return Type

An Array of terminated substrings of the string resulting by the termination of the string by matches substring by given regular expression

Exception

Throws PatternSyntaxException if regular expression syntax is not valid

Examples Java String Class split() Method

  1. Example of Java String Class split() method without specified limit
package com.java.test;
 
public class ExampleStringSplit {

    private void splitString() {

          int i = 0;

          String str = "Welcome to String class split() function learning";

          // Split String from each space character

          String[] strSplitArray = str.split("\\s");

          int lenghtOfSplitStringArray = strSplitArray.length;
 
          System.out.println("Split String Array size = " + lenghtOfSplitStringArray);
 
          System.out.println("Splitted String returned array values");

          for (String splitString : strSplitArray) {

          System.out.println("Substring #" + ++i + " = " + splitString);
  
         }
 
    }
 
    public static void main(String[] args) {
 
         ExampleStringSplit example = new ExampleStringSplit();
         example.splitString();

     }
}

 
OutPut:

Split String Array size = 7

Splitted String returned array values

Substring #1 = Welcome

Substring #2 = to

Substring #3 = String

Substring #4 = class

Substring #5 = split()

Substring #6 = function

Substring #7 = learning

2. Example of Java String Class split() method with specified limit

package com.java.test;
 
public class ExampleStringSplit {
 
    private void splitStringWithLimit() {

          int i = 0;

          String str = "Welcome to String class format function learning";

          // Split String from space character upto maximum limit 4

          String[] strSplitArray = str.split("\\s", 4);

          int lenghtOfSplitStringArray = strSplitArray.length;

          System.out.println("Splitted String returned Array size = " + lenghtOfSplitStringArray);

          System.out.println("Splitted String returned Array values");

          for (String splitString : strSplitArray) {
 
         System.out.println("Substring #" + ++i + " = " + splitString);

          }
 
    }
 
    public static void main(String[] args) {

          ExampleStringSplit example = new ExampleStringSplit();

          example.splitStringWithLimit();

     }

}
 

Output:

Splitted String returned Array size = 4

Splitted String returned Array values

Substring #1 = Welcome

Substring #2 = to

Substring #3 = String

Substring #4 = class format function learning

3. Example to throw PatternSyntaxException

package com.java.test;
 
public class ExampleStringSplit {
 
    private void splitStringWithLimit() {

          int i = 0;

          String str = "Welcome to String class format function learning";

          // Split String from space character upto maximum limit 4
          String[] strSplitArray = str.split("\\o", 4);

          int lenghtOfSplitStringArray = strSplitArray.length;

          System.out.println("Splitted String returned Array size = " + lenghtOfSplitStringArray);

          System.out.println("Splitted String returned Array values");

          for (String splitString : strSplitArray) {

                 System.out.println("Substring #" + ++i + " = " + splitString);

          }
 
    }
 
    public static void main(String[] args) {

          ExampleStringSplit example = new ExampleStringSplit();

          example.splitStringWithLimit();

     }

}
 

Output:

Exception in thread "main" 

java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 1

\o

 ^

    at java.util.regex.Pattern.error(Pattern.java:1957)

    at java.util.regex.Pattern.escape(Pattern.java:2473)

    at java.util.regex.Pattern.atom(Pattern.java:2200)

    at java.util.regex.Pattern.sequence(Pattern.java:2081)

    at java.util.regex.Pattern.expr(Pattern.java:1998)

    at java.util.regex.Pattern.compile(Pattern.java:1698)

    at java.util.regex.Pattern.<init>(Pattern.java:1351)

    at java.util.regex.Pattern.compile(Pattern.java:1028)

    at java.lang.String.split(String.java:2380)

    at com.java.test.ExampleStringSplit.splitStringWithLimit(ExampleStringSplit.java:9)

    at com.java.test.ExampleStringSplit.main(ExampleStringSplit.java:21)

Other Methods of String Class

SequenceMethodDescription
1char charAt(int index)This method is used to return the character of the string at specified index. First character is at index 0 while last is at string length-1 . StringIndexOutOfBounds Exception is thrown if valid index value is not passed.
2int length()Returns the number of characters count  in  a string.
3static String format(String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s).
4static String format(Locale l, String format, Object… args)Return the formatted String. It is a static method and formats the string as per passing format and argument(s) and locale.
5String substring(int beginIndex)Returns substring from the given index position to the end index of the string.
6String substring(int beginIndex, int endIndex)Returns substring from the specified begin index to the specified end index.
7boolean contains(CharSequence s)Returns boolean value(true/false). It searches the given sequence of characters within the string and returns true/false accordingly. Characters will be case sensitive while searching in string.
8static String join(CharSequence delimiter, CharSequence… elements)Returns joined string. This method joins each passing String using the specified delimiter. It is a static method.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)Returns the joined string. This method joins each passing string object of an iterate object using the specified delimiter and returns the concatenated string. It is a static method.
10boolean equals(Object another)Returns boolean value(true/false). It checks the equality of string with the passing object.
11boolean isEmpty()Returns boolean value(true/false). It returns true if the string is empty otherwise returns false.
12String concat(String str)Returns the concatenating string. It concatenates the passing string at the end of the string.
13String replace(char old, char new)Return the replaced string. It replaces all occurrences of the specified character with the new character.
14String replace(CharSequence old, CharSequence new)Return the replaced string. It replaces all occurrences of the specified Character sequence with the specified new Character sequence.
15String replaceAll(String regex, String replacement)Returns the replaced string. It replaces all occurrences of the sequence of characters with the given replacement string that are matching with the given regular expression.
16String replaceFirst(String regex, String replacement)Returns the replaced string. It replaces the first matching sequence of characters with the replacement string that matches with the given regular expression.
17static boolean equalsIgnoreCase(String another)Returns the boolean (true/false) value. It compares the passing string with string by ignoring the case. It  compares the content irrespective of lowercase or uppercase of the character(s).
18String intern()Returns an interned string. This method helps to compare two objects using == operator and checks in a string constant pool. it is faster for comparison.
19int indexOf(int ch)Returns the index value of first occurrence of the specified character within the string
20int indexOf(int ch, int fromIndex)Returns the index value of first occurrence of the specified character from the substring starting from specified index
21int indexOf(String substring)Returns the index value of first occurrence of the specified substring within the string.
22int indexOf(String substring, int fromIndex)Returns the index value of the first occurrence of the specified string within the substring starting from specified index to end of the string index.
23int lastIndexOf(int ch)Returns the index value of last occurrence of the specified character
24int lastIndexOf (int ch, int fromIndex)Returns the index value of last occurrence of the specified character, search starts at given fromIndex. 
25int lastIndexOf (String str)Returns the index value of last occurrence of the specified string.
26int lastIndexOf (String str, int fromIndexReturns the index value of last occurrence of the specified string, searches start from given fromIndex
27String toLowerCase()Returns all the characters of the string in lowercase .
28String toLowerCase(Locale l)Returns all the characters of the string in lowercase using specified locale.
29String toUpperCase()Returns all the characters of the string in uppercase.
30String toUpperCase(Locale l)Returns all the characters of the string in uppercase using specified locale.
31String trim()Returns the string after removing the white space from the beginning and end of the string.
32static String valueOf(int value)Return the converted string. It converts the objects and all primitive types of values into string. It is a static method.

In this article, we learned all about the split() method of String class with examples. Apart from the split() method we got an idea about other String methods too. We will come up with more articles explaining other String methods description with examples. For more details please click on the respective methods link.

Leave a Reply

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