6 minutes read

The Standard library in Go has many handy packages. In this topic, we are going to explore the strings package, especially its part concerning modification and splitting operations.

Changing the case of a string

Package strings implements simple functions to manipulate UTF-8 encoded strings. To start using this package, we need to import it to the current file:

import "strings"

One of the basic operations with strings is changing its case. When working with a string, you may need to carry out some operations with it disregarding its case. Hence, converting a string to lower or upper case is convenient. To map the characters of a given string to the lowercase, we can use the strings.ToLower function:

func ToLower(s string) string

For example:

question := "What Does The Fox Say?"
fmt.Println(strings.ToLower(question))

// Output:
// what does the fox say?

To map characters of a string to the upper case, use the ToUpper function:

quote := "Are you not entertained?!\nIs this not why you are here?!"
fmt.Println(strings.ToUpper(quote))

// Output:
// ARE YOU NOT ENTERTAINED?!
// IS THIS NOT WHY YOU ARE HERE?!

Trimming strings

Sometimes the initial data in a string may have some unnecessary symbols at the beginning or at the end. How can we solve this? Let's introduce the strings.Trim function:

func Trim(s, cutset string) string

This function is helpful when you need to get rid of certain symbols from both sides of a given string.

secret := "STATUS%1337%ENDSTATUS"
fmt.Println(strings.Trim(secret, "ADENSTU%"))

// Output:
// 1337

Pay attention that the second argument of the Trim function is a cutset, and the function will remove any character present in this cutset from both sides of the string.

If you need to get rid of symbols that are only in the beginning or at the end of the target string, there are two more specialized functions for it:

func TrimLeft(s, cutset string) string
func TrimRight(s, cutset string) string

As you may suggest from the names of these functions, they remove symbols from one side of a given string.

One more helper from the family of trim functions is strings.TrimSpace. It removes space characters, such as \n\r\t from both ends of the strings:

outerSpace := "    \tOuter Space...  \r\n"
fmt.Println(strings.TrimSpace(outerSpace))

// Output:
// Outer Space...

Separating and concatenating

Most strings consist of words, sentences, or some encoded data with a special format. We can split the string and work with the resulting slice to get these pieces. Let's learn how we can do it!

The Split function "splits" the target string by a given separator into a slice of strings:

phoneNumber := "8800-555-35-35"
fmt.Println(strings.Split(phoneNumber, "-"))

juiceDayDate := "18/September"
fmt.Println(strings.Split(juiceDayDate, "/"))

// Output:
// [8800 555 35 35]
// [18 September]

The reverse operation is called joining. As you may have already guessed, it joins a slice of strings into a single string by a provided separator:

taunt := []string{
    "Oh",
    "You want to fight",
    "Instead of running, you're coming towards me?!",
}
fmt.Println(strings.Join(taunt, "?!\n"))

// Output:
// Oh?!
// You want to fight?!
// Instead of running, you're coming towards me?!

Wiping out words from strings

Another example of a problem we might want to solve is replacing some part of a string, whether it's because of typos or creating a new string with new data.

If you want to change several appearances of a certain word, strings.Replace is here to save the day:

banned := "You Have Been Banned From The Minnie Mouse Club"
fmt.Println(strings.Replace(banned, "Minnie", "Mickey", 1))

// Output:
// You Have Been Banned From The Mickey Mouse Club

The last argument of the Replace function is the maximum number of substitutions of the pattern in the given string. The special case is the negative number then we replace all the occurrences.

ReplaceAll does the same job, except it changes all appearances of a specific word:

func ReplaceAll(s, old, new string) string
wrongChorus := `
Behind the world, around the world
Around the world, behind the world
Behind the world, around the world
`

correctedChorus := strings.ReplaceAll(wrongChorus, "Behind", "Around")
correctedChorus = strings.ReplaceAll(correctedChorus, "behind", "around")

fmt.Println(correctedChorus)

// Output:
// Around the world, around the world
// Around the world, around the world
// Around the world, around the world

Conclusion

In this topic, we have looked at the commonly used functions from the strings package:

  • Changing the case of a string with ToLower, ToUpper;

  • Trimming certain symbols from string, using Trim, TrimRight, TrimLeft, and TrimSpace;

  • Splitting a string and joining slices of strings into a new string;

  • Replacing a substring from a string with the use of the Replace and ReplaceAll functions.

36 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo