Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to extract a substring from a string in Golang

Gutha Vamsi Krishna

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
communitycreator
RELATED COURSES

View all Courses

Keep Exploring