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...

Using Makefiles For Go (GoLang) Development

Using Makefiles For Go (GoLang) Development

Learn how to run, build and, compile Go (GoLang) Applications for any Platform and Operating System using a Makefile

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang

Sorting Slices In Go

Sorting Slices In Go

Learn How To Sort Slices in GoLang