Substring in GoLang

Substrings are a part of a string. Creating it from a string is really easy in Go. This post covers the best possible ways to generate substring from a string.

Get a single character from a string

Getting a single character can be done using simple indexing. Here is an example.

package main

import (
	"fmt"
)

func main() {
	var s string
	s = "Hello"
	
	fmt.Println(string(s[1]))   // e
}

Remember to convert it into a string as shown in the code, otherwise, it will return the ASCII code.

Using range based slicing to create a substring

Taking a range from a slice will extract a substring. This is really easy to do. We simply take a range and get it out from the original string.

package main

import (
	"fmt"
)

func main() {
	s := "Hello World"
	fmt.Println(s[1:4])   // ell
}

Range-based extraction is a simple way of handling substring generation from a string.

Using the split method

The split method provides a way to split a string using a character. Here is a simple example showing that.

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Hello!World"
	fmt.Println(strings.Split(s, "!"))   // [Hello World]
}

This method returns an array of substrings generated from all of the splits using that character.

Regular expressions can also be used to split a string in Go.

Check if a string is a substring

To check that simply using the Contains method work. The method is in the “strings” package.

package main
 
import (
	"strings"
    	"fmt"
)
 
func main() {
	s := "Hello World"
	sr := strings.Split(s, " ")                  // create substring
	fmt.Println(strings.Contains(s, sr[0]))      // true
}

Which method to use

To create substring in Go there are many options available. The slicing from an original string is the most intuitive of them all. It is also one of the most efficient methods available. The other methods are very specific and require careful considerations for substring creation from a string.