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
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis