by @codeexamples

How to split a string in Java

Home » java » How to split a string in Java

To split a string we need to use the String.split() method by passing a regular expression as an argument in Java.

Here is an example which splits the string by a delimiter dot .

String name = "code.examples";

String[] output = name.split("\\."));

System.out.println(output[0]);
System.out.println(output[1]);

Output:

code
examples

Note: The period/dot is a special character in regex so that we have used double backslashes (\\) to escape it.

Other example:

String phone = "1334-345-5465";

String[] output = phone.split("-");

System.out.println(output[0]);
System.out.println(output[1]);
System.out.println(output[2]);

Output:

1334
345
5465