Split a string around a particular match in Java

Java 8Object Oriented ProgrammingProgramming

The specified string can be split around a particular match for a regex using the String.split() method. This method has a single parameter i.e. regex and it returns the string array obtained by splitting the input string around a particular match for the regex.

A program that demonstrates splitting a string is given as follows:

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      String regex = "_";
      String strInput = "The_sky_is_blue";
      System.out.println("Regex: " + regex);
      System.out.println("Input string: " + strInput);
      String[] strArr = strInput.split(regex);
      System.out.println("\nThe split input string is:");
      for (String s : strArr) {
         System.out.println(s);
      }
   }
}

Output

Regex: _
Input string: The_sky_is_blue
The split input string is:
The
sky
is
blue

Now let us understand the above program.

The regex and the input string is printed. Then the input string is split around the regex value using the String.split() method. Then the split input is printed. A code snippet which demonstrates this is as follows:

String regex = "_";
String strInput = "The_sky_is_blue";
System.out.println("Regex: " + regex);
System.out.println("Input string: " + strInput);
String[] strArr = strInput.split(regex);
System.out.println("\nThe split input string is:");
for (String s : strArr) {
   System.out.println(s);
}
raja
Published on 19-Feb-2019 07:29:27
Advertisements