×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.SplitN() Function with Examples

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

strings.SplitN()

The SplitN() function is an inbuilt function of strings package which is used to split the given string (slice) into all substrings by the given separator. It accepts three parameters – a slice (string), a separator, and N (number of substrings to return), and returns a slice of the N substrings between those separators.

Note:

  • If N is greater than o, then SplitN() returns most N substrings, and the last substrings will be the unsplit remainder.
  • If N is equal to 0, the result is Nil.
  • If N is less than 0, all substrings will be returned.

Syntax

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

Parameters

  • str : The string (slice) whose value is to be separated.
  • sep : Separator.
  • N : Number of substrings to be returned.

Return Value

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

Example 1

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

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.SplitN("The sun is very bright", " ", 1))
	fmt.Printf("%q\n", strings.SplitN("The sun is very bright", " ", 3))
	fmt.Printf("%q\n", strings.SplitN("The sun is very bright", " ", 0))
	fmt.Printf("%q\n", strings.SplitN("The sun is very bright", " ", -1))
	fmt.Printf("%q\n", strings.SplitN("a man a plan a canal panama", "a ", 4))
	fmt.Printf("%q\n", strings.SplitN("The sun is very bright", "", -1))
	fmt.Printf("%q\n", strings.SplitN("", ",", -1))
}

Output:

["The sun is very bright"]
["The" "sun" "is very bright"]
[]
["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.SplitN() Function

package main

import (
	"fmt"
	"strings"
)

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

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.