How to extract a substring from a string in Golang
In this shot, we will learn how to extract a substring from a string using Golang.
Syntax
string[starting_index : ending_index]
Note:
starting_indexis inclusive and theending_indexis exclusive, while extracting the substring.
Return value
It returns a new string.
Example
In the following example, we use the string educative and extract a substring from index 2 to the end of the string.
The end of the string is calculated by using the length of the string.
Code
package main//import the packagesimport("fmt")//program execution starts from herefunc main() {//declare and initialize the stringstr := "educative"// Take substring from index 2 to length of stringsubstr := str[2:len(str)]//display the extracted substringfmt.Println(substr)}
Code explanation
In the code snippet above:
-
Line 5: We import the
fmtpackage, which is useful for printing the input and output. -
Line 9: The program execution starts from the
main()function in Golang. -
Line 12: We declare and initialize the string
str. -
Line 15: We extract the substring from the string
strfrom index2to the end of the string (len(str)). -
Line 18: We display the extracted substring
substr.