8 Most used functions of strings pkg in Go

| Reading Time : 4 minutes | #backenddevelopment #Go


Introduction

The standard Go library strings package provides many string related functions. This blog lists description of most frequently used function of strings package in Go, Since there are a lot of functions available and it’s not easy to remember each one of those straight away, it worth bookmarking as it might be handy when needed. Below is a list of function with small example snippet code.

Note: I am amateur in Go if you are an experienced professional in Go and find anything wrong here don’t be annoyed if you could point the mistake I will correct those accordingly.

1 .Compare

compares two string lexicographically Outcome of this function is an integer and could be either 0, -1 or 1

Function signature :

func Compare(a, b string) int

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Compare("gopher19", "gopher20"))
	fmt.Println(strings.Compare("gopher19", "gopher19"))
	fmt.Println(strings.Compare("gopher20", "gopher19"))
}

Output :
-1
0
1

2 .Contains

contains function returns an appropriate Boolean value if given substring present in the string being searched.

Function signature :

func Contains(s, substr string) bool

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Contains("gopher-20", "20"))
	fmt.Println(strings.Contains("gopher-20", "30"))
	fmt.Println(strings.Contains("gopher-20", ""))
	fmt.Println(strings.Contains("", ""))
}

output:
true
false
true
true

3 .Count

I find this most useful especially in coding challenges where they ask you to find number of times a character repeated in a string.

This function takes two strings as input and checks number of times second string argument appears in first string argument and returns count as an integer.

Function signature :

func Count(s, substr string) int

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Count("gopher-gopher-gopher", "g"))
	fmt.Println(strings.Count("gopher", "g"))
}

output:
3
1

4 .Fields

If you ever wanted to split a string into string array by white space characters

This function takes a string as input and splits into an array by white space characters in the string and returns a string array.

Function signature :

func Fields(s string) []string

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("Fields are: %q", strings.Fields("gopher is sleeping."))
}

output:
Fields are: ["gopher" "is" "sleeping."]

5 .HasPrefix

This function takes two strings as input and checks if the second argument string is present in starting characters of the first argument string.

.HasPrefix has his brother called .HasSuffix does exactly same but this time it checks at the ending part of the string.

Function signature :

func HasPrefix(s, prefix string) bool

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.HasPrefix("gopher", "go"))
	fmt.Println(strings.HasPrefix("gopher", "java"))
	fmt.Println(strings.HasPrefix("gopher", ""))
}

output:
true
false
true

6 .Replace

This function takes four parameters as input

  • culprit string
  • old string
  • new string
  • number of times new string will replace old string in culprit string

if n < 0 there is no limit on a number of replacements.

Function signature :

func Replace(s, old, new string, n int) string

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Replace("no-banana no-banana no-banana", "no", "yes", 2))
	fmt.Println(strings.Replace("no-banana no-banana no-banana", "no", "yes", -1))
}

output:
yes-banana yes-banana no-banana
yes-banana yes-banana yes-banana

another version of .Replace is .ReplaceAll which basically replace all.

7 .Split

This function takes two strings as input and returns a slice of the substrings based on the second argument string.

Function signature :

func Split(s, sep string) []string

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Printf("%q\n", strings.Split("gopher,19,gopher", ","))
}

output:
["gopher" "19" "gopher"]

There are few more variations of .Split exists which are .SplitAfter .SplitAfterN .SplitN

8 .TrimSpace

One of the most used feature to remove white spaces, this function takes a string as input and returns a string with trailing and leading spaces removed.

Function signature :

func TrimSpace(s string) string

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.TrimSpace(" \t\n Covid-19's vaccine will be invented and out soon to rescue us all from this insane. \n\t\r\n"))
}

output:
Covid-19's vaccine will be invented and out soon to rescue us all from this insane.

This is the end of the most-used strings functions I think are, but if you think there is something which you think must go into this list please drop me a message and I will include it in here.


Articles from blogs I follow around the net

powerctl: A small case study in Hare for systems programming

powerctl is a little weekend project I put together to provide a simple tool for managing power states on Linux. I had previously put my laptop into suspend with a basic “echo mem | doas tee /sys/power/state”, but this leaves a lot to be desired. I have to u…

via Drew DeVault's blog August 28, 2022

United States v. Microsoft Corp exhibits

Links to exhibits from the Microsoft anti-trust case, with a bit of info on each link. Projection of PC marketshare Share of new browser users Share of the browser market, grouped by major ISP, 3 month moving average Share of the browser market, grouped by ma…

via danluu.com August 24, 2022

Status update, August 2022

Hi all! This month I’ve been pondering offline-first apps. The online aspect of modern apps is an important feature for many use-cases: it enables collaboration between multiple people and seamless transition between devices (e.g. I often switch between my pe…

via emersion August 14, 2022

Generated by openring

© Copyright 2021-2022. Rakesh Mothukuri