Core Java

How to split a string in java

Here are some approaches to split a String in Java.


  • Using String.split() method
  • Using StringTokenizer


Splitting a string using the split() method


Here is the syntax of the split() method :


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



regex is a regular expression that will act as separator for the method.

limit is an optional parameter that decides substrings will be returned.


Here is an example on how to use the split() method:


Here is the output :

Splitting a string using StringTokenizer method


StringTokenizer is a legacy class that can be used to Split a string.


Here is the output:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.

Consider using the split method of String or the java.util.regex package instead.


© 2015, All rights reserved.