Skip Top Navigation Bar

Splitting a String of Characters with split() - Example 2

Snippet: Splitting a Text to Lines, and Each Line to Fields

Explanation

This snippet shows how to use split() at two levels to parse a simple CSV-like text. First, the multi-line string is split on "\n" (newline) to get individual lines. Then, inside a for-each loop, each line is split on ";" to extract the name and age fields.

The text block (the """...""" syntax) is a convenient way to write multi-line strings in Java. It preserves the line breaks, which makes splitting on "\n" work naturally.

What You Can Do

Try adding a third field to each line — for example, a city — and update the print statement to display it. What index would you use to access it?

You can also try changing the delimiter from ";" to "," and updating the data accordingly. This is how real CSV files typically look. Does the snippet still work the same way?

Run it and observe the output!

Example List

Additional Resources