Ayomide Ayanwola
TheCodeWay

Follow

TheCodeWay

Follow

Working with strings effectively with Golang

Part 1: Peeking into strings

Ayomide Ayanwola's photo
Ayomide Ayanwola
ยทOct 9, 2022ยท

4 min read

Play this article

Table of contents

What are Strings? ๐Ÿค”

The way strings is stored in memory makes them immutable, making it difficult to perform simple operations like changing the value of an index in a string. For example you can't perform an index assignment operation on a string, but this is possible with arrays. Golang has a built-in library that can help us work with strings. We are able to read and manipulate strings in various ways.

In this tutorial series, we would discuss about ways we can manipulate a string in Golang. By looking into

  • Peeking,
  • Traversing,
  • Mutating, and
  • Sorting

of strings in Golang, you should be confident enough to work with them in any aspect of programming you come across.

Working with Strings ๐Ÿ›ฉ๏ธ

Peeking

In this use case Peeking means inspecting a string trying to find what it looks like. For example, checking the first character of a string, the character at an index, the characters in a range of two index, etc.

Testing the first and last characters of a string

We can test what starts (prefixes) and ends (suffixes) a string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var str string = "Hashnode is a very easy tool to use for blogging"
    fmt.Printf("T/F? \nDoes the string \"%s\" have prefix %s? ", str, "Th")
    fmt.Printf("\n%t\n\n", strings.HasPrefix(str, "Th"))    // Finding prefix

    fmt.Printf("Does the string \"%s\" have suffix %s? ", str, "ting")
    fmt.Printf("\n%t\n\n", strings.HasSuffix(str, "ing"))  // Finding suffix
}

Run code live here

Output:

T/F? 
Does the string "Hashnode is a very easy tool to use for blogging" have prefix Th? 
false

Does the string "Hashnode is a very easy tool to use for blogging" have suffix ting? 
true

From the output above, the function HasPrefix checks whether the string in its first parameter starts with the Th. The function HasSuffix does the opposite of that, it checks the end of the string. The HasPrefix function returns false because the string in variable str doesn't start with Th. While HasSuffix returned true because the string str ends with ing.

The above methods show a simple way to test what starts and ends any string.

Indexing a string

For beginners, indexing a string in Go for the first time will seem weird. When you index a string in Go you get a rune. The Go language defines the word rune as an alias for the type int32. Read more about string in Go

Take the following code sample as an example;

package main

import (
    "fmt"
)

func main() {
    var str string = "Hashnode is a very easy tool to use for blogging"
    fmt.Println(str[0])
}

Run code live here

Output

72

Converting the rune to a string gives the actual character at that index.

package main

import (
    "fmt"
)

func main() {
    var str string = "Hashnode is a very easy tool to use for blogging"
    fmt.Println(string(str[0]))
}

Run code live here

Output

H

Testing if a string contains a substring

To check if a string contains some string, do the following

package main

import (
    "fmt"
    "strings"
)

func main() {
    var str = "I code Python, Golang, JavaScript, TypeScript and PHP"
    fmt.Println(strings.Contains(str, "Golang"))
    fmt.Println(strings.Contains(str, "Rust"))
}

Run code live here

Output

true
false

The function Contains returns true if the second parameter is found in the first parameter. Otherwise, it returns false.

Locating the index of a substring or character in a string

We can locate the first or last occurrence of a substring or character in a string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var str string = "Hi, I'm Marc, Hi."
    fmt.Printf("The position of the first instance of\"Marc\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Marc")) // Finding first occurence
    fmt.Printf("The position of the first instance of \"Hi\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Hi")) // Finding first occurence
    fmt.Printf("The position of the last instance of \"Hi\" is: ")
    fmt.Printf("%d\n", strings.LastIndex(str, "Hi")) // Finding last occurence
    fmt.Printf("The position of the first instance of\"Burger\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Burger")) // Finding first occurence
    fmt.Printf("%d\n", strings.IndexRune(str, 'H'))  // Finding first occurence
}

Run code live here

Output

The position of the first instance of"Marc" is: 8
The position of the first instance of "Hi" is: 0
The position of the last instance of "Hi" is: 14
The position of the first instance of"Burger" is: -1
0

Index returns the index of the first instance of the second parameter in the first parameter. LastIndex searches from the end of the string, returning the index of the last occurrence of the character or substring in the searched string. IndexRune returns the index of the first instance of the Unicode code point 'H' in the string str.

To be continued

Hope you learned something new today!. This part of the String series focuses on how you can test the values of a string in Go. You can practice more of the functions covered in this tutorial. To master and do more practice check out the Strings module documentation. Learn on your own how to use strings.Count to count the number of occurences of a character or substring in a string.

In the next part, we would look at ways a string can be manipulated in Go. Thanks for reading.

ย 
Share this