How to replace a single character inside a string in Golang?

前端 未结 2 582
甜味超标
甜味超标 2020-12-23 16:39

I am getting a physical location address from a user and trying to arrange it to create a URL that would use later to get a JSON response from Google Geocode API.

Th

相关标签:
2条回答
  • 2020-12-23 17:27

    If you need to replace all occurrences of the character in the string, then use strings.ReplaceAll:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        str := "a space-separated string"
        str = strings.ReplaceAll(str, " ", ",")
        fmt.Println(str)
    }
    
    0 讨论(0)
  • 2020-12-23 17:33

    You can use strings.Replace.

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        str := "a space-separated string"
        str = strings.Replace(str, " ", ",", -1)
        fmt.Println(str)
    }
    

    If you need to replace more than one thing, or you'll need to do the same replacement over and over, it might be better to use a strings.Replacer:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    // replacer replaces spaces with commas and tabs with commas.
    // It's a package-level variable so we can easily reuse it, but
    // this program doesn't take advantage of that fact.
    var replacer = strings.NewReplacer(" ", ",", "\t", ",")
    
    func main() {
        str := "a space- and\ttab-separated string"
        str = replacer.Replace(str)
        fmt.Println(str)
    }
    

    And of course if you're replacing for the purpose of encoding, such as URL encoding, then it might be better to use a function specifically for that purpose, such as url.QueryEscape

    0 讨论(0)
提交回复
热议问题