Menu Close

Go – SplitN() function in strings package in go

Here, We will learn about SplitN() function in strings package in go.  SplitN() function is used to slices string into substrings separated by separator  in go golang.

Function prototype:

func SplitN(str, sep string, n int) []string

Return value:

SplitN() function in strings package do 
slices string into substrings separated by
separator and returns a slice of the substrings
between those separators.

Here, count determines the number of substrings to return:

n == 0 : the result is nil (zero substrings)
n < 0: all substrings
n > 0: at most n substrings and the last substring
will be the unsplit remainder.

Example with code:

package main
 
import (
  "fmt"
  "strings"
)
 
func main() {
 
  s := strings.SplitN("a,b,c", ",", 2)
  fmt.Println(s)
 
  s = strings.SplitN("Hello Go Golang", "o", 1)
  fmt.Println(s)
 
  s = strings.SplitN("abc", "", 3)
  fmt.Println(s)
 
  s = strings.SplitN("a,b,c", ",", 1)
  fmt.Println(s)
 
  s = strings.SplitN("xyz", ",", 2)
  fmt.Println(s)
 
  s = strings.SplitN("xyz", "p", 3)
  fmt.Println(s)
 
 
}

Output:

[a b,c]
[Hello Go 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 *