golang

Golang Substring

A substring refers to a sequence of characters contained within a larger set of strings. In most cases, you will need to extract a part of a string to save it for future use.

This guide will explore various methods to extract a substring from a string in the go programming language.

Extract Single Character

You can extract a single character from a string by using its index. Consider the example shown below:

packagemain
import "fmt"
funcmain() {
    str := "Hello"
    char := string(str[1])
    fmt.Println(char)
}

We extract a character from a string using its index in the example above. Since going returns an ascii code for that specific character, we need to convert it back to a string.

Range Based Slicing

Another method to extract a substring in Go is to use range-based slicing. We can specify the starting and stopping index for the target index we wish to extract.

An example is as shown below:

packagemain
import "fmt"
funcmain() {
    str := "Welcome to Linuxhint"
    fmt.Println(str[10:])
}

The example above extracts the substring starting from index 10 to the last index of the string. The resulting substring is as:

Linuxhint

Using range-based slicing is one of the most effective ways of generating a substring in go.

You can also slice in the middle of the string, as shown in the example below:

packagemain
import "fmt"
funcmain() {
    str := "Welcome to Linuxhint"
    fmt.Println(str[0:7])
}

This example extracts the substring from index 0 to index 7. We can also replace the above syntax as shown:

packagemain
import "fmt"
funcmain() {
    str := "Welcome to Linuxhint"
    fmt.Println(str[:7])
}

The above syntax works similar to the previous one but eliminates the 0 index. The resulting substring is as:

Welcome

Split Method

You can also use the split method to extract a substring in go. The method separates strings based on the specified character.

Consider the example below:

packagemain
import (
    "fmt"
    "strings"
)
funcmain() {
    str := "Welcome to Linuxhint"
    extract := strings.Split(str, " ")
    fmt.Println(extract[0])
}

In the example above, we use the split method to separate the string using spaces. This creates an array of individual string elements from the main string. We can then use indexing to access each item.

The resulting substring is as:

Welcome

Conclusion

This guide explores how you can extract a substring from a string. Although some of the methods are more intuitive and readable than others, it is good to consider the operations that need to be performed when extracting a specific string.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list