Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
strings.Split() Function in Golang
strings.Split() is used to break a string into a list of substrings using a specified delimiter. It returns the substrings in the form of a slice.
Syntax
The syntax of strings.Split() is as follows −
func Split(S string, sep string) []string
Where s is the given string and sep is the delimiter (separator) string. It returns the substrings.
Example 1
Let us consider the following example −
package main
import (
"fmt"
"strings"
"regexp"
)
func main() {
// Intializing the Strings
p := "oopsfunctions"
q := "GoLang language"
// Display the Strings
fmt.Println("String 1:", p)
fmt.Println("String 2:", q)
// Using the Split Function and regexp
r := regexp.MustCompile(`[ns]`)
s := r.Split(p, -2)
t := strings.Split(q, "Lang")
u := strings.Split(p, "")
// Display the Split Output
fmt.Println("Split String 1: ", s)
fmt.Println("Split String 2: ", t)
fmt.Println("Split String 1 with delimiter:", u)
}
Output
It will generate the following output −
String 1: oopsfunctions String 2: GoLang language Split String 1: [oop fu ctio ] Split String 2: [Go language] Split String 1 with delimiter: [o o p s f u n c t i o n s]
Example 2
Let us take another example.
package main
import (
"fmt"
"strings"
)
func main() {
var x string
var y string
var w string
// Intializing the Strings
x = "Hello! World"
y = "This, is, a, sample, program"
w = "1-2-3-4"
// Display the Strings
fmt.Println("String 1:", x)
fmt.Println("String 2:", y)
fmt.Println("String 3:", w)
// Using the Split Function
res1 := strings.Split(x, "!")
res2 := strings.Split(y, ",")
res3 := strings.Split(w, "-")
res4 := strings.Split(y, "a")
// Display the Split Output
fmt.Println("Split String 1:", res1)
fmt.Println("Split String 2:", res2)
fmt.Println("Split String 3:", res3)
fmt.Println("Split String 2 with delimiter:", res4)
}
Output
It will generate the following output −
String 1: Hello! World String 2: This, is, a, sample, program String 3: 1-2-3-4 Split String 1: [Hello World] Split String 2: [This is a sample program] Split String 3: [1 2 3 4] Split String 2 with delimiter: [This, is, , s mple, progr m]
Advertisements