String manipulation in Golang

String manipulation in Golang

Using common string operations in Go


4 min read

Once you've learned enough syntax of a programming language, the best way to put in practice what you've learned so far is to start building an application. From my experience, for a very large number of applications ( web applications especially) the most common data type in the code is the string data type.

If you're building a web service , for example, a lot of the user input is going to be some type of text, and it will be passed either in the request body, the query string , or perhaps in the request headers.

So, working with strings is one of the most important parts of the job.

When working with strings in Go, for most of the operations you will need a module that is part of the Go standard library, and it is called - well, strings ( I like it when things are obvious) .

So let's look at some code snippets and explain what they do along the way:

package main

import (

func main() {

    fruits := "apple,orange,kiwi,peach"
    fruitSlice := strings.Split(fruits, ",")

This one should be pretty straightforward. Like every Go file, we start by specifying the package name and defining what we will import. Since we plan to run this file as an executable, we will put it in the main package, and define the main function.

I created a string called fruits, but I need it to be a slice. With the use of the strings module, a simple call of the Split function gives me the result I need.

Next, I want to see what my fruit string will look with all of the letters capitalized:

capitalized := strings.ToUpper(fruits)

Pretty easy. By now you've realized that the main difference between string manipulation in Go and an object oriented language like Python is that in Python we would call the split method directly on the string object e.g fruits.split(',')

But, since Go is not an OOP language, you pass the string as a function parameter . It's basically just a different approach, but the result is quite similar. The function names are also pretty similar to ones that we know from manipulating strings in Python , JavaScript and other popular languages.

Let's look at a couple of more examples that are common for working with strings.

Here we want to replace all occurrences of the word "Bucks" with the word "Lakers" ( my apologies to Bucks fans) .

sentence := "The Bucks are the NBA champions. Go Bucks !"
newSentence := strings.ReplaceAll(sentence, "Bucks", "Lakers")

In the next one we are trimming the white space of a string, which is really useful when comparing two strings. I would always suggest trimming strings when comparing them, especially if the strings that are being compared are the result of splitting a larger string in to a slice of strings. I have witnessed a number of bugs in applications that were caused due to not trimming strings before comparing them.

    // lets compare the equality of two strings:
    whiteSpacedSentence := "   Hello World   "
    regularSentence := "Hello World"
    if whiteSpacedSentence == regularSentence {
        fmt.Println("they're the same")
    } else {
        fmt.Println("they're NOT the same")
    // now let's trim the first string:
    trimmedSentence := strings.TrimSpace(whiteSpacedSentence)
    if trimmedSentence == regularSentence {
        fmt.Println("they're the same")
    } else {
        fmt.Println("they're NOT the same")

One last operation that I would like to mention concerned with strings is the conversion of different data types to strings. In Go, there are two approaches.

The first looks like this:

byteSlice := []byte{72, 101, 108, 108, 111}
stringFromBytes := string(byteSlice)

Here we have a byte slice containing some numbers and when you convert it to a string type you get a word that is used in english for greeting people. The numbers represent what the characters are in ASCII encoding when converted to bytes.

However, if you try this on an integer, the Go compiler will have an unpleasant message for you, in the manner of conversion from int to string yields a string of one rune, not a string of digits .

Basically it is telling us that it will not convert the integer to a string , but rather to a rune, which is basically going to be its ASCII value. We don't want that, we just want a string , plain and simple.

Luckily, the Go standard library has a module that will solve this issue easily. It's called strconv, and the function is called Itoa ( I know, they're not very descriptive, but remember the creators of Go were inspired in part by C and that's what it was called in C ) .

Here's the code:

num := 38
numToString := strconv.Itoa(num)

That's it for this article. In the next articles I plan to write about more modules from the Go standard library that are essential for developing real applications.

Thanks for reading!

Did you find this article valuable?

Support Pavle Djuric by becoming a sponsor. Any amount is appreciated!