Splitting Lines: Fields, Split and Cut
Once you have a line, you need to break it into parts. The strings package has three tools you'll reach for most often.
strings.Fields: split on spaces
Fields splits a string at every run of spaces (tabs included), and never produces empty parts:
strings.Fields(" 3 x 12000 ") // ["3" "x" "12000"]
It suits input whose columns are separated by spaces, however many spaces there are.
strings.Split: split on an exact separator
Split breaks the string at every occurrence of the separator, exactly. Two separators side by side leave an empty string between them:
strings.Split("4,8,,15", ",") // ["4" "8" "" "15"]
strings.Split("a b", " ") // ["a" "b"]
strings.Split("a b", " ") // ["a" "" "b"]
Use Split for separators like a comma or "\n", and Fields for spaces.
strings.Cut: split only once
Often a line has the shape key: value, and the key itself may contain spaces. Cut cuts at the first occurrence of the separator and tells you whether it found it:
item, rest, found := strings.Cut("green tea: 3 x 12000", ": ")
// item = "green tea", rest = "3 x 12000", found = true
If found is false, the line doesn't match the format. Don't ignore it: return an error.
Check the shape before you index
fields[2] on a slice with only two elements panics. Check len(fields) first, then convert the numbers with strconv.Atoi and handle the error.
Task
A small shop logs orders in the format <item>: <qty> x <price>, for example green tea: 3 x 12000. An item's name can be several words long.
- Complete
parseOrder(line string) (Order, error). Cut withstrings.Cut(line, ": "), then split the rest withstrings.Fields. The rest must be exactly three parts withxin the middle. Return an error if there's no": ", if the number of parts is wrong, or if the quantity and price aren't whole numbers. - Complete
total(input string) (int, error): add upQty * Pricefor every line that isn't blank. If any line is wrong, return its error.