C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Golang program that uses Fields method
package main
import (
"fmt"
"strings"
)
func main() {
value := "Cat Dog Bird Fish"
result := strings.Fields(value)
// Display all fields, first field and count.
fmt.Println(result)
fmt.Println(result[0])
fmt.Println(len(result))
}
Output
[Cat Dog Bird Fish]
Cat
4
Tip: With FieldsFunc, we get the same functionality as Fields() but are not restricted to using a space separator.
Golang program that uses FieldsFunc
package main
import (
"fmt"
"strings"
)
func main() {
// Return true if comma or colon char.
f := func(c rune) bool {
return c == ',' || c == ':'
}
// Separate into fields with func.
fields := strings.FieldsFunc("cat,dog:bird", f)
fmt.Println(fields)
}
Output
[cat dog bird]