Mastering String Search and Replace in Go

Overview and Actualizing the Topic

Hello, learners! In today's session, we will explore searching and replacing strings in Go. Imagine this scenario: you're operating a chat service and need to filter and replace certain inappropriate words. This lesson will show you how to accomplish this task using Go's standard strings package.

String Searching: the `strings.Index` and `strings.LastIndex` Functions

Let's start with string searching. Go offers the strings.Index and strings.LastIndex functions. strings.Index returns the index of the first occurrence of a substring, while strings.LastIndex provides the index of the last.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Hello, CodeSignal learners!"
    fmt.Println(strings.Index(str, "CodeSignal")) // Output: 7, as str[7:16] = "CodeSignal"
}

In this example, the string "CodeSignal" begins at index seven in our string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "CodeSignal is fun. I love CodeSignal!"
    fmt.Println(strings.LastIndex(str, "CodeSignal")) // Output: 26
}

Notice how "CodeSignal" starts at index 26 in the last instance within our string. Efficient, isn't it?

Checking Substring Existence: the `strings.Contains` Function

The strings.Contains function checks whether a string contains a particular sequence of characters, regardless of their position.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Welcome to CodeSignal!"
    fmt.Println(strings.Contains(str, "CodeSignal")) // Output: true
}

This code sample proves that "CodeSignal" indeed is present in our string. These practical functions enable us to handle real-world situations!

String Replacement: the `strings.ReplaceAll` Function

Replacing specific elements within strings can be easily accomplished in Go with the strings.ReplaceAll function. This function replaces all instances of the provided string with another string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "Apples are sweet. I love apples! Apples are healthy as well."
    fmt.Println(strings.ReplaceAll(str, "Apples", "Oranges")) // Output: "Oranges are sweet. I love apples! Oranges are healthy as well."
}

Note that "apples" hasn't been replaced: it is because we are replacing "Apples", starting with an uppercase A at the beginning. Go treats strings "Apples" and "apples" as different strings.

This replacement function can modify file paths or fix user inputs, seamlessly incorporating changes!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal