How to split a string in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

Splitting a string means being able to get a part of a string, and that part can either be based on a position or a character in the string.

In Go, if we want to split a string on the basis of positions, we can make use of the [ ] (square brackets) and then pass the indices in them separated by a colon.

Syntax

Consider the syntax shown below.

sl[startingIndex : EndingIndex]

It should be noted that the element at the EndingIndex in the slice won't be considered, as the range is from startingIndex to (EndingIndex−1).

Example 1

Now, let's consider an example where we will split a string on the basis of different positions.

Consider the code shown below.

package main

import (
"fmt"
)

func main() {
var secretString string = "this is a top secret string"

res := secretString[0:10]

res2 := secretString[:5]

res3 := secretString[10:]

fmt.Println(res, res2, res3)
}

Output

If we run the command go run main.go in the above code, then we will get the following output in the terminal.

this is a this top secret string

Example 2

We can also split the string in Go on the basis of a particular character. Consider the code shown below.

package main

import (
"fmt"
"reflect"
"strings"
)

func main() {
var secretString string = "this is not a top secret string"

res := strings.Split(secretString, "n")

checkType := reflect.TypeOf(res)

fmt.Println(res)

fmt.Println(checkType)
}

In the above example, we are splitting the string on the basis of character "n". It will result in a slice where there will be two values inside it, the first will contain all the characters that occurred before the character 'n' and then all the ones after it.

Output

If we run the command go run main.go in the above code, then we will get the following output in the terminal.

[this is ot a top secret stri g]
[]string
Updated on 03-Mar-2022 13:33:43