Skip to content

Split and Validate a Line

The Course
•
18 min study

The reading log will accept one session per line in the form title,minutes, such as Poems,25. Before the program can check a session, it has to take that line apart. People type spaces in odd places and sometimes forget the comma altogether, so taking a line apart safely is a small but real piece of validation.

strings.Cut(s, ",") splits text at the first comma and returns three results: the text before it, the text after it and whether a comma was found. strings.TrimSpace removes spaces from both ends. The reading log needs both steps before it can check the title and the minutes.

Predict and run

What is left after trimming each field?

Predict, then run Go
package main

import (
	"fmt"
	"strings"
)

func main() {
	title, raw, found := strings.Cut(" Poems , 25 ", ",")
	if found {
		fmt.Println(strings.TrimSpace(title))
		fmt.Println(strings.TrimSpace(raw))
	}
}
Check your prediction
Text
Poems
25

Remove the comma and predict what the program prints.

Three results from one call

strings.Cut returns three values, and you receive them all in one := statement, in order: before, after and found. When there is no comma, before is the whole input, after is the empty string and found is false. Checking found is how you tell Poems (no comma, invalid) apart from Poems, (a comma with nothing after it). Use _ for any result you really do not need.

Cut splits only at the first comma. Everything after that comma, including any further commas, ends up in after. For the reading log that is what you want: A,b,3 splits into the title A and the minutes text b,3, which then fails conversion with a clear error instead of being quietly misread.

Lines that go wrong Go
package main

import (
	"fmt"
	"strings"
)

func main() {
	for _, line := range []string{"Poems,25", "A,b,3", "No comma", "Essays,"} {
		title, raw, found := strings.Cut(line, ",")
		fmt.Printf("%q %q %v\n", title, raw, found)
	}
}
Text
"Poems" "25" true
"A" "b,3" true
"No comma" "" false
"Essays" "" true

Printing with %q shows each field's exact edges, including empty strings, which would be invisible with %s.

Trimming

strings.TrimSpace returns a copy of a string with whitespace removed from both ends. Whitespace includes spaces, tabs and newline characters, but not the spaces inside the text, so " Short stories " becomes "Short stories". Strings in Go cannot be changed in place, so like append, TrimSpace returns the new value and you store it, usually back into the same variable: title = strings.TrimSpace(title).

Trim each field after splitting

Trimming the whole line before splitting removes the spaces at its outer ends, but not those next to the comma, such as the space in Poems , 25. Trim each field after Cut and every edge is handled, which is what the reading log does.

After splitting, validate the parts

A line can split cleanly and still be invalid. After trimming, an empty title should be rejected, because a report line with no title is useless. The minutes text still needs strconv.Atoi and a range check. Put the checks in the order the line is read: comma first, then title, then minutes. That way each message describes the first problem a person would want to fix.

The strings package

strings has many other small, reliable helpers, such as strings.ToUpper, strings.HasPrefix and strings.Contains. When you need to do something common with text, look there before writing a loop yourself. For splitting a line into exactly two parts, though, Cut is the clearest choice, because its found result makes the missing-separator case impossible to forget.

Practice

Exercise

Your turn

Split " Essays , 30 " and print Essays: 30. Print Invalid instead when the comma is missing.

Your working space Go
package main

func main() {
	// Write your code here.
}
Hint 1: the idea

The third result says whether both fields exist.

Hint 2: a first step

Use strings.Cut and keep all three results.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"strings"
)

func main() {
	title, raw, found := strings.Cut(" Essays , 30 ", ",")
	if !found {
		fmt.Println("Invalid")
		return
	}
	fmt.Printf("%s: %s\n", strings.TrimSpace(title), strings.TrimSpace(raw))
}
Text
Essays: 30

Remove the comma to test the other branch. return ends main early, so the success line never runs.

Was this article helpful?

Your response is saved on this device.