programming

Get to know the Standard String Library in Golang

As programmers who are learning Go Lang, we also need to know Go’s default library packages so that we understand better and have an easier time interacting with the core packages. There are lots of built-in libraries from Golang that can make it easier for us when coding. For example, if we need string conversion, the Go library is provided by default.

For further details, we will discuss one by one the libraries that we think need to be studied to support us when coding.

Strings

Go includes several functions that work with string processing, including the following examples:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(
		// true
		strings.Contains("test", "es"),
		// 2
		strings.Count("test", "t"),
		// true
		strings.HasPrefix("test", "te"),
		// true
		strings.HasSuffix("test", "st"),
		// 1
		strings.Index("test", "e"),
		// "a-b-c"
		strings.Join([]string{"a", "b","c"}, "-"),
		// == "aaaaa"
		strings.Repeat("a", 5),
		// "bbaa"
		strings.Replace("aaaa", "a", "b", 2),
		// []string{"a","b","c","d","e"}
		strings.Split("a-b-c-d-e", "-"),
		// "test"
		strings.ToLower("TEST"),
		// "TEST"
		strings.ToUpper("test"),
	)
}

We can see several functions contained in the string library that we can use for several operations.

  • The Contains function is very useful if we are looking for data that in one variable contains the data we want to select.
  • The Count function is used to count the selected characters in a sentence or word.
  • We can also use the HasPrefix function to detect if a word contains the first letter te so it will be easier to use this function.
  • The HasSuffix function is used to detect whether it has a suffix that matches the letter we entered.
  • The Index function is useful for finding out what index the character we are looking for is at the index in the sentence or word.
  • The Join function is used to combine an array of letter characters into one sentence/word with a delimiter added.
  • The Repeat function is used to repeat as many inputs as we want.
  • The Replace function is used to overwrite a character/word from a word that we have specified.
  • The Split function is used to retrieve string data from characters with a certain delimiter.
  • The ToLower function is used to make words / characters all lowercase.
  • The ToUpper function is used for words / characters to be capitalized.

It’s very easy, isn’t it? Golang has provided supporting functions to make it easier for us to operate it.

Sometimes we need to use strings as binary data. To convert a string to a chunk of bytes (and vice versa) it can be done like this

arr := []byte("test")
str := string([]byte{'t','e','s','t'})

And there are many more supporting functions for manipulating strings that are provided by Golang. You can also see the String Library [here] (https://blog.golang.org/strings).

comments powered by Disqus