by Sai gowtham

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course