Codiqo

Learn Java · lesson 36 of 61 · about 9 minutes

Splitting and Joining

Read an online booking: break text into parts with split, and put parts back together with String.join.

What you'll learn

  • Split on spaces and commas
  • Join parts with a separator
  • Parse simple CSV lines

An online booking

Bookings made on the website arrive at the desk as one line of text, like Bo,2,17:30: a name, how many tickets, and a showing. split(",") cuts it into an array of three parts, Integer.parseInt turns the middle one into a number, and the time is checked against today's showings with equals. A line that doesn't have exactly three parts can't be read, so the desk checks length before using any part. The showings themselves are listed with String.join(" / ", times).

Split and join

  • "a,b,c".split(",") gives an array ["a", "b", "c"]
  • text.trim().split("\\s+") splits on any run of spaces
  • String.join(", ", parts) joins an array or list with a separator

Parsing a CSV line

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String line = "Ada,12,python";
        String[] parts = line.split(",");
        String name = parts[0];
        int age = Integer.parseInt(parts[1]);
        System.out.println(name + " is " + age + " and learns " + parts[2]);

        String[] words = "  learn   to code ".trim().split("\\s+");
        System.out.println(words.length + " " + Arrays.toString(words));
        System.out.println(String.join("-", words).toUpperCase());
    }
}

Output

Ada is 12 and learns python
3 [learn, to, code]
LEARN-TO-CODE

Tip

split takes a regular expression. \\s+ means "one or more whitespace characters". To split on a dot you'd write "\\.", because a plain dot means "any character".

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.