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:
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:
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:
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:
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:
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:
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:
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:
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.