Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

1. Introduction

In this short tutorial, we'll cover some of Go's String's functions that developers use daily.

2. Get the Length of a String

To get the length of a String, we'll use the len() function.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Get the String Length.
	fmt.Println(len("GoLang")) // prints 6

3. Convert String to Title Case

To convert a string to title case, we'll use the Title() function.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Convert String to Title Case.
	fmt.Println(strings.Title("go is fun to learn.")) // Prints "Go Is Fun To Learn."

}

4. Check if a String Starts with a Substring

To check if a string starts with a substring, we'll use the HasPrefix() function.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Check if String Starts with a SubString.
	fmt.Println(strings.HasPrefix("GoLang", "Go")) // prints true

}

5. Check if String Ends with SubString

To check if a string ends with a substring, we'll use the HasSuffix() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
  
	// Check if String Ends with SubString.
	fmt.Println(strings.HasSuffix("GoLang", "ng")) // prints true
}

6. Compare if Two Strings are Equal (Ignore Case)

To compare if two strings are equal, we'll use the EqualFold() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
  
	// Compare if Two Strings are Equal (Ignore Case).
	fmt.Println(strings.EqualFold("GOLANG", "golang")) // prints true

}

7. Conclusion

In this short tutorial, we'll learn how to use some of the base Go String functions. You can find the source code on GitHub

Did you like it? Why don't you try also...

How to remove the last character of a string in Golang

How to remove the last character of a string in Golang

Learn how to remove the last character of a string in GoLang

Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.

How to Find the Minimum Integer Value In a GoLang Slice

How to Find the Minimum Integer Value In a GoLang Slice

Learn to Find the minimum Integer Value In a GoLang Slice