Menu Close

Go – How to split strings in go golang

Here, We will learn how to split strings in go. We can do it by using Split() function in strings package in go golang. Split() function do slices of string into all substrings separated by separator.

Function prototype:

func Split(str, sep string) []string

Return value:

Split() function in strings package returns 
slice of the substrings between those separators.

If string does not have separator and separator is
not empty then split() function returns string only.

Example with code:

package main

import (
  "fmt"
  "strings"
)

func main() {

  s := strings.Split("a,b,c", ",")
  fmt.Println(s)

  s = strings.Split("Hello Go Golang", "o ")
  fmt.Println(s)

  s = strings.Split("abc", "")
  fmt.Println(s)

  s = strings.Split("a,b,c", ",")
  fmt.Println(s)

  s = strings.Split("xyz", ",")
  fmt.Println(s)

  s = strings.Split("xyz", "p")
  fmt.Println(s)

  s = strings.Split("", ",")
  fmt.Println(s)
	
}

Output:

[a b c]
[Hell G Golang]
[a b c]
[a b c]
[xyz]
[xyz]
[]

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, strings

Leave a Reply

Your email address will not be published. Required fields are marked *