Golang Code

Search and Replace in a String

· 155 words · 1 minute read #strings #search #replace #occurrance #escape #quotes

As programmers we often need to take a string and replace parts of it with something else. The code has three examples, first of which is a basic ‘find all’ and replace, the second changes only the first occurance of ‘sound’ and finally the third example demonstrates how to change a string containing quotes to use escaped quotes.

All this functionality is managed by the strings package and the Replace function.

package main

import (

func main() {
    // Example 1: Basic
    myText := "Welcome to GoLangCode.com"
    myText = strings.Replace(myText, "Welcome", "Willkommen", -1)

    // Output: Willkommen to GoLangCode.com

    // Example 2: Change first occurance
    myText = "The sound sounds sound"
    myText = strings.Replace(myText, "sound", "car", 1)

    // Output: The car sounds sound

    // Example 3: Replacing quotes (double backslash needed)
    myText = "I 'quote' this text"
    myText = strings.Replace(myText, "'", "\\'", -1)

    // Output: I \'quote\' this text
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!