How to split a string in Java?

Java 8Object Oriented ProgrammingProgramming

Java provides a split() methodology you'll be able to split the string around matches of the given regular expression.

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. 

If the expression doesn't match any a part of the input then the ensuing array has the only 1part, specifically this string.


Live Demo

import java.lang.*;

public class StringDemo {
   public static void main(String[] args) {

      String str = "a d, m, i.n";
      String delimiters = "\s+|,\s*|\.\s*";
      String[] tokensVal = str.split(delimiters);
      // prints the count of tokens
      System.out.println("Count of tokens = " + tokensVal.length);    
      for(String token : tokensVal) {
      tokensVal = str.split(delimiters, 3);
Count of tokens = " + tokensVal.length);                 for(String token : tokensVal) {          System.out.print(token);       }        } }


Count of tokens = 5
Count of tokens = 3
adm, i.n
Updated on 16-Jun-2020 11:58:57