golang

Learn How to print Substring in Golang


In this article, you will learn about how to print Substring in the Go language.

In the Go language, strings are nothing but a slice of bytes that is immutable. You can easily generate a substring in the Go language. It is a part of String. Before jump into generating a substring from a string, lets see an example of String in the Go language :

package main

import (
        "fmt"
)

func main() {
       
        var Mystring string
        Mystring = "Good Morning"

        fmt.Println(Mystring)
}

// Output: Good Morning

You can generate substring in many different ways. We will explore one by one but at first we see create a substring by getting a single character from the string. See the example below:

package main

import (
        "fmt"
)

func main() {
        
        var Mystring string
        Mystring = "Good Morning"

        fmt.Println(string(Mystring[5]))
}

// Output : M

Here we get the character M because we have mentioned the index number of the slice is 5. If you want to get another character then you have to mention the index number of that particular character that you want to print.

You can also generate a substring by defining a range of slices. It is most popular approach and easy to use in the Go language. Example:

package main

import (
        "fmt"
)

func main() {
        
        Mystring := "Good Morning"

        fmt.Println(Mystring[0:4])
}

// Output: Good

Using the split method is another way of generating substring in the Go language. All you need to do is to define the character you want to split and then it will split the string based on the mentioned character and generate a substring. See the below code example to get things more clear:

package main

import (
        "fmt"
        "strings"
)

func main() {

        Mystring := "Good-Morning"

        fmt.Println(strings.Split(Mystring, "-"))
}

// Output: Good Morning

Share on social media

//