Skip to content
ExamSpine

Lesson 5.10

Split a line into parts; join parts

Part 5: Text, lists, stacks and queuesReading, about 6 min3 exercises in this lesson

Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.

Splitting a line into parts

By the end of this you will be able to split a line of text into parts, at its spaces or at a separator such as a comma, use each part by its position, loop over the parts, and join parts back into one line.

Programs often get several things in one line of text: the words of a sentence, or a name and an age typed with a comma between them. Splitting turns that one text value into a list of smaller text values, one for each part. From then on it is a list (an array in Java), and everything you know about reading arrays and lists by position works on it.

Splitting at the spaces

line = "the cat sat down"
words = line.split()
print(len(words))
print(words[0])
print(words[len(words) - 1])
public static void main(String[] args) {
    String line = "the cat sat down";
    String[] words = line.split(" ");
    System.out.println(words.length);
    System.out.println(words[0]);
    int last = words.length - 1;
    System.out.println(words[last]);
}

When it runs, it prints:

4
the
down

split gives a list of the parts, in the order they come in the line. The spaces themselves are not in any part: they are only where the line is cut. In Python, split() with nothing in the brackets splits at the spaces, and gives a list. In Java, split(" ") splits at each space, and gives an array of String values, written String[].

The line itself does not change. Splitting makes a new list and leaves the text as it was.

Splitting at another separator

Data often uses a comma between its parts. Put the separator in the brackets, in both languages.

record = "Kofi,16,blue"
parts = record.split(",")
name = parts[0]
age = int(parts[1])
print(name + " will be " + str(age + 1))
print("Favourite colour: " + parts[2])
public static void main(String[] args) {
    String record = "Kofi,16,blue";
    String[] parts = record.split(",");
    String name = parts[0];
    int age = Integer.parseInt(parts[1]);
    System.out.println(
        name + " will be " + (age + 1));
    System.out.println(
        "Favourite colour: " + parts[2]);
}

When it runs, it prints:

Kofi will be 17
Favourite colour: blue

Every part is text, even when it looks like a number. parts[1] is the text "16", so it is turned into a whole number before any sums are done with it, the same way as a number read from input.

When you know what each position holds, give each part a name, as name and age do here. A name says more than parts[1] each time it is used.

In Java, split reads its separator as a pattern (called a regular expression), not just as plain text. A space and a comma mean just themselves, so split(" ") and split(",") work as you would expect. A few characters, such as a full stop, have a special meaning in a pattern, and this course keeps to separators like spaces and commas.

Looping over the parts

The parts are a list, so a loop can visit each one. This counts the words that have more than three letters.

line = "a big red balloon floated away"
count = 0
for word in line.split():
    if len(word) > 3:
        count = count + 1
print(count)
public static void main(String[] args) {
    String line =
        "a big red balloon floated away";
    int count = 0;
    for (String word : line.split(" ")) {
        if (word.length() > 3) {
            count = count + 1;
        }
    }
    System.out.println(count);
}

This prints 3: "balloon", "floated" and "away". Each part is a text value, so len(word) in Python, or word.length() in Java, is its number of characters.

Two spaces in a row

The lines so far have exactly one space between words. Real typing is not always so tidy, and here the two languages behave differently.

The line in this program has two spaces between "red" and "green".

line = "red  green"
print(line.split())
print(line.split(" "))
public static void main(String[] args) {
    String line = "red  green";
    String[] parts = line.split(" ");
    System.out.println(parts.length);
    System.out.println("[" + parts[1] + "]");
}

In Python, the program prints ['red', 'green'] and then ['red', '', 'green']. split() with nothing in the brackets treats a run of spaces as one cut, and ignores spaces at the start and the end. Put a space in the brackets, as split(" "), and Python cuts at every single space instead, so there is an empty text value between the two spaces.

In Java, the program prints 3 and then []. split(" ") cuts at every single space, so the array has three values: "red", an empty text value, and "green". The brackets around parts[1] show that there is nothing in it. A space at the start of the line gives an empty value at the start too. Empty values at the very end are dropped.

An empty value has length 0. If a program counts the parts as words, it counts it as a word. When the input might have extra spaces, check for empty parts in Java (or use split() with nothing in the brackets in Python).

A common mistake: assuming every part has something in it. If a part can be empty, parts[0] might be "", and reading a character from it stops the program with an error.

Joining the parts back up

Joining is the opposite of splitting: it makes one text value from a list of parts, with a separator between each pair.

words = "the cat sat".split()
joined = "-".join(words)
print(joined)
public static void main(String[] args) {
    String[] words =
        "the cat sat".split(" ");
    String joined = String.join("-", words);
    System.out.println(joined);
}

This prints the-cat-sat. The separator goes only between parts, never after the last one. In Python the separator comes first and join is called on it. In Java, String.join takes the separator and then the parts.

The pattern to remember

Split at the separator, and you have a list. Use a part by its position when you know what each position holds, and loop over the parts when each one is treated the same. Every part is text until you turn it into a number. Now try it yourself on the questions below.

Exercise 5.10.15.10.1 · Write itReverse the words

Write a function that returns a sentence with its words in reverse order.

  1. The words are separated by exactly one space, with no space at the start or the end. Words contain only letters, digits and punctuation.
  2. Punctuation stays with the word it is attached to, and each word keeps its capital letters.
  3. Empty text returns empty text.
  4. Put exactly one space between the words you return, and none at the start or the end.

Only the text your function returns is checked, exactly.

def reverse_words(sentence: str) -> str

Examples

Your function is tested on 9 cases: the 5 examples below, and 4 hidden ones that check the rules above.

  • reverse_words("the cat sat") should return "sat cat the": three words in reverse order
  • reverse_words("hello") should return "hello": one word stays as it is
  • reverse_words("Hi there, friend!") should return "friend! there, Hi": punctuation stays with its word (rule 2)
  • reverse_words("") should return "": empty text gives empty text (rule 3)
  • reverse_words("to be or not to be") should return "be to not or be to": the first word and the last word each appear twice

public static String reverseWords(String sentence)

Checking whether Java answers can run here.

Examples

Your function is tested on 9 cases: the 5 examples below, and 4 hidden ones that check the rules above.

  • reverseWords("the cat sat") should return "sat cat the": three words in reverse order
  • reverseWords("hello") should return "hello": one word stays as it is
  • reverseWords("Hi there, friend!") should return "friend! there, Hi": punctuation stays with its word (rule 2)
  • reverseWords("") should return "": empty text gives empty text (rule 3)
  • reverseWords("to be or not to be") should return "be to not or be to": the first word and the last word each appear twice
solution.pySolution.java

Exercise 5.10.25.10.2 · Write itThe longest word

Write a function that returns the longest word in a sentence.

  1. The words are separated by exactly one space, with no space at the start or the end. There is always at least one word, and words contain only letters.
  2. If two or more words are equally long, return the first of them.
  3. Return the word exactly as it is in the sentence.
  4. Write the search yourself. The shortcuts listed with this question are not allowed.

Only the text your function returns is checked, exactly.

def longest_word(sentence: str) -> str

You cannot use these in this question:

  • max()
  • min()
  • sorted()
  • .sort()
  • import heapq

Practise splitting and the longest-so-far loop by writing them yourself. The shortcuts listed are not allowed.

Examples

Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.

  • longest_word("a big elephant") should return "elephant": the longest word is the last word
  • longest_word("the quick brown fox") should return "quick": quick and brown are equally long, so the first wins (rule 2)
  • longest_word("I like it") should return "like": a later word shorter than the longest so far, but longer than the first word
  • longest_word("sun") should return "sun": one word

public static String longestWord(String sentence)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Arrays.sort()
  • Arrays.parallelSort()
  • Collections.max()
  • Collections.min()
  • .sort()
  • .stream()
  • .max()
  • .min()
  • import java.util.stream

Practise splitting and the longest-so-far loop by writing them yourself. The shortcuts listed are not allowed.

Examples

Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.

  • longestWord("a big elephant") should return "elephant": the longest word is the last word
  • longestWord("the quick brown fox") should return "quick": quick and brown are equally long, so the first wins (rule 2)
  • longestWord("I like it") should return "like": a later word shorter than the longest so far, but longer than the first word
  • longestWord("sun") should return "sun": one word
solution.pySolution.java

Exercise 5.10.35.10.3 · Write itScores on one line

Write a program that reads one line holding a name and some test scores, and prints a short report.

  1. The line has the name first, then one or more scores. The parts are separated by commas, with no spaces around the commas. For example: Ana,72,85,90.
  2. The name has no commas in it, but it can have spaces. Every score is a whole number from 0 to 100.
  3. Print three lines: Name: and the name, then Scores: and how many scores there are, then Total: and the scores added up.

For the example line, the program prints:

Name: Ana
Scores: 3
Total: 247

Your program is run several times. Only what it prints is checked.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 2 examples below, and 4 hidden ones that check the rules above. Only what it prints is checked.

  • the example: a name and three scores (rule 3)

    You type

    1. typed: Ana,72,85,90

    It prints

    Name: Ana
    Scores: 3
    Total: 247
  • a name and only one score (rule 1)

    You type

    1. typed: Leo,50

    It prints

    Name: Leo
    Scores: 1
    Total: 50
solution.pySolution.java