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.

Example

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) {
         System.out.print(token);
      }      
      tokensVal = str.split(delimiters, 3);
      System.out.println("\nCount of tokens = " + tokensVal.length);    
     
      for(String token : tokensVal) {
         System.out.print(token);
      }    
   }
}

Output

Count of tokens = 5
admin
Count of tokens = 3
adm, i.n
raja
Published on 10-Jan-2018 12:26:22
Advertisements