Golang strings.Split() Function with Examples

Golang | strings.Split() Function: Here, we are going to learn about the Split() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 19, 2021

strings.Split()

The Split() function is an inbuilt function of strings package which is used to split the given string (slice) into all substrings separated by the given separator. It accepts two parameters – a slice (string) and a separator and returns a slice of the substrings between those separators.

Note:

  • If the slice does not contain a separator and the separator is not empty, the Split() function returns a slice of length 1 whose only element is the given string.
  • If separator is empty, Split() function splits after each UTF-8 sequence. If both the string and separator are empty, the Split() function returns an empty slice.

Syntax:

func Split(str, sep string) []string

Parameter(s):

  • str : The string (slice) whose value is to be separated.
  • sep : Separator.

Return Value:

The return type of Split() function is a []string, it returns a slice of the substrings between those separators.

Example 1:

// Golang program to demonstrate the
// example of strings.Split() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.Split("The sun is very bright", " "))
	fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
	fmt.Printf("%q\n", strings.Split("The sun is very bright", ""))
	fmt.Printf("%q\n", strings.Split("", ","))
}

Output:

["The" "sun" "is" "very" "bright"]
["" "man " "plan " "canal panama"]
["T" "h" "e" " " "s" "u" "n" " " "i" "s" " " "v" "e" "r" "y" " " "b" "r" "i" "g" "h" "t"]
[""]

Example 2:

// Golang program to demonstrate the
// example of strings.Split() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.Split("The#sun#is#very#bright", "#"))
	fmt.Printf("%q\n", strings.Split("The, sun, is, very, bright", ", "))
	fmt.Printf("%q\n", strings.Split("Delhi Mumai Indore Gwalior", " "))
}

Output:

["The" "sun" "is" "very" "bright"]
["The" "sun" "is" "very" "bright"]
["Delhi" "Mumai" "Indore" "Gwalior"]

Golang strings Package Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.