Split a string in Java

I am writing some java code and there is certain requirement where need to split certain numbers which looks like,

5555-9999-7777 (which will be split into 3 different parts)

Need some suggestion on this.


You can use the StringTokenizer or String.split(String regex).

1) If you use the StringTokenizer st=new  StringTokenize(string,delimeter)----> delimeter is the expression is the matching string

Iterate over the st.hasMoreTokens.

2) String.split()

String[] splittedString= string.split("-");

Note that this takes a regular expression, so remember to escape special characters if necessary. E.g. if you want to split on period/dot . which means "any character" in regex, use either backslash to escape the individual special character like so split("."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on period.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");

No, this does not take a regular expression.

Answer is