In this shot, we will learn how to extract a substring from a string using Golang.
string[starting_index : ending_index]
Note:
starting_index
is inclusive and theending_index
is exclusive, while extracting the substring.
It returns a new string.
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.
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)}
In the code snippet above:
Line 5: We import the fmt
package, 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 str
from index 2
to the end of the string (len(str)
).
Line 18: We display the extracted substring substr
.