Split String From a String in Golang — GolangLearn

Parvez Alam
2 min readOct 24, 2021

in this tutorial, We’ll split a string from a string using golang inbuilt method. The golang strings package has split() method to create a substring from a string. The Split slices sting into all substrings separated by separator and return a slice of the substrings between those separators.

Split returns a slice of length 1 whose lone element is a string if the separator is not empty. Split splits after each UTF-8 sequence if the separator is empty. Split returns an empty slice if both the string and the separator are empty.

Goalng String

The Golang has a string package that’ll have all string manipulation methods. We can create an empty string, multiline string, concate, etc using go. All inbuilt strings functions are stored in the standard library “strings” package. We just need to include the string package at the top of the go file and use its method. You can get more information from Official Docs.

The Structure of Golang String Types:

The following is the structure of any string type is declared:

type _string struct { elements *byte // underlying bytes len int // number of bytes }

Split A String in Golang

Let’s split a string using split() method. This function splits a string into all substrings separated by the separator specified and returns a slice containing these substrings.

The split() method will return the original string if the separator does not found in the source string, if found, then it will return all splits strings.

The Syntax

The following is the syntax of golang split() method:

func Split(str, sep string) []string The params are:

str — This is the source string.
sep — This is the separator.

You can also use strings.SplitAfter. To split only the first n values, use strings.SplitN and strings.SplitAfterN.

Split a string and assign to variables:

package main import ( "fmt" "strings" ) func main() { s := strings.Split("127.0.0.1:3010", ":") ip, port := s[0], s[1] fmt.Println(ip, port) }

The Output:

127.0.0.1 3010

Split String Using Separator

Split by whitespace and newline Using Fields()

The Fields function divides a string into substrings by removing any spaces, including newlines.

s := strings.Fields(" Adam \t Joe \n") fmt.Println(s)

Output:

[Adam Joe]

Split String Using Regular Expression

It divides a string into substrings using a regular expression to separate them. The method takes an integer n as an argument and returns at most n substrings if n > 0.

a := regexp.MustCompile(a) fmt.Printf("%q\n", a.Split("Adam Joe", -1)) fmt.Printf("%q\n", a.Split("Adam Joe", 0))

Output:

["Ad" "m Joe"] [] ["Adam Joe"]

Originally published at https://www.golanglearn.com on October 24, 2021.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/