Library contents

Go strings.Split

Split an ordinary record on commas to count its fields.

A simple example

strings.Split

  1. Start with a,b
  2. Do this Split at the comma
  3. Result a and b
The comma separates two nonempty fields.
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "a,b"
    fmt.Println(len(strings.Split(value, ",")))
}
Output
2

Syntax

Go syntax
len(strings.Split(value, ","))
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Count stops in a shuttle record

A timetable or route import divides each record at separators. Test the behavior at an empty field so later columns do not shift when the writer leaves a value blank.

From the programvalue := "Gate,Lab,Hall"
Result3
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "Gate,Lab,Hall"
    fmt.Println(len(strings.Split(value, ",")))
}
Output
3

Three nonempty stop fields are present.

Advertisements

Handle an express route

A transit editor changes selected text in a route while preserving its remaining stops or punctuation. Identify which occurrences belong to the requested edit before rebuilding the public route label.

From the programvalue := "Depot"
Result1
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    value := "Depot"
    fmt.Println(len(strings.Split(value, ",")))
}
Output
1

With no delimiter the complete route is one field.

Count a choir equipment list

A teacher receives one comma-separated line of items. Split the record at each comma. Each field is nonempty, so the station can count the resulting entries directly.

Givenmic,stand,cable
Worked result3

What to watch for

These examples use simple unquoted fields. Use a CSV reader for quoted values or embedded commas.

Documentation for strings.Split