Start learning free

LESSON 63 OF 671 · STRINGS I

String Split in Java

Lesson

In Java, you can split a string into an array of substrings using split(). It takes a regular expression as the delimiter:

s.split(regex)   // splits using a regex delimiter

Here are some examples:

String sentence = "hello world foo";
String[] words = sentence.split(" ");
// words == ["hello", "world", "foo"]

String csv = "a,b,c";
String[] parts = csv.split(",");
// parts == ["a", "b", "c"]

You can loop through the resulting array:

for (String w : words) {
    System.out.println(w);
}

Assignment
Follow the Coding Tutorial and split sentence into a String array!


Hint
Use sentence.split(" ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check