Home » Golang String Cut Function

Golang String Cut Function

Cut() Function in Golang strings package is used to cut the slices of the given string around the first instance of sep.

It returns the text before and after the sep and the boolean value if the sep appears in the given string. If the sep is not present in the given string, the Cut() function returns an empty string and false.

Cut() Syntax

The syntax for Cut() function is:

func Cut(s1, sep string) (before, after string, found bool)

Cut() Parameters:

The Cut() function takes two parameters

s1 is the string
sep is the string

Cut() Return Value

The strings package Cut() function returns the text before and after the sep and boolean true value if sep is present in the given string else false.

Let’s understand the string package Cut() method with examples.

strings.Cut() function to cut a string in go

The following go program cuts the string s1 around the first instance of sep using the strings.Cut() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	show := func(s1, sep string) {
		before, after, found := strings.Cut(s1, sep)
		fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s1, sep, before, after, found)
	}
	show("GolangSpot", "Go")
	show("GolangSpot", "lang")
	show("GolangSpot", "Spot")
	show("GolangSpot", "program")
	show("GolangSpot Go Hub", "Go")
}

The output of the above program is:

Cut("GolangSpot", "Go") = "", "langSpot", true
Cut("GolangSpot", "lang") = "Go", "Spot", true
Cut("GolangSpot", "Spot") = "Golang", "", true
Cut("GolangSpot", "program") = "GolangSpot", "", false
Cut("GolangSpot Go Hub", "Go") = "", "langSpot Go Hub", true

In the above program,

The first output returns the text before and after sep “Go” in the given string “GolangSpot“. It returns a true value as sep appears in the string.

The second output returns the text before and after of sep “lang” in the given string “GolangSpot“. It returns a true value as sep appears in the string.

The third output returns the text before and after of sep “Spot” in the given string “GolangSpot“. It returns a true value as sep appears in the string.

The fourth output returns the text before and after the sep “program” in the given string “GolangSpot” as empty, It returns a false value as sep doesn’t appear in the string.

The fifth output returns the text before and after of sep “Go” in the given string “GolangSpot Go Hub". Cut function slice the string around the first instance of Go.

Cool Tip: How to use the string EqualFold function in Golang!

Conclusion

I hope the above article on Cut the slice around the first instance of sep string using the Cut() method is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment