Trusted answers to developer questions

How to extract a substring from a string in Golang

Gutha Vamsi Krishna

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

In this shot, we will learn how to extract a substring from a string using Golang.

Syntax

string[starting_index : ending_index]

Note: starting_index is inclusive and the ending_index is 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 packages
import(
"fmt"
)
//program execution starts from here
func main() {
//declare and initialize the string
str := "educative"
// Take substring from index 2 to length of string
substr := str[2:len(str)]
//display the extracted substring
fmt.Println(substr)
}

Code explanation

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.

RELATED TAGS

golang

CONTRIBUTOR

Gutha Vamsi Krishna
Trusted Answers to Developer Questions

Related Tags

golang
Did you find this helpful?