PaolaJ.
PaolaJ.

Reputation: 11532

Replace specific characters with appropriate characters in given word

I want to in words in sentence change every occurrence of 'n' with 'm', 'a' with 'e' and 10 more rules. At the moment I am working calling sequental way for every rule like:

word = strings.Replace(word, "n", "m", -1)
word = strings.Replace(word, "a", "e", -1)
.... and 10 more times 

Is there better way to replace in Go characters with another, given in map?

Upvotes: 2

Views: 1127

Answers (4)

icza
icza

Reputation: 417572

Basically this is what the strings.Map() function is for.

Map returns a copy of the string s with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement.

Example (try it on the Go Playground):

func main() {
    fmt.Println(strings.Map(rules, "Try not to replace me"))
}

func rules(r rune) rune {
    switch r {
    case 'n':
        return 'm'
    case 'a':
        return 'e'
    default:
        return r
    }
}

Output:

Try mot to replece me

With a map

If you have many rules, you can shorten this code:

var repMap = map[rune]rune{
    'a': 'e', 'n': 'm',
}

func rules2(r rune) rune {
    if r2, ok := repMap[r]; ok {
        return r2
    }
    return r
}

Output is the same (Go Playground).

Upvotes: 5

赵浩翔
赵浩翔

Reputation: 653

package main
import (
    "fmt"
    "strings"
)

func main() {
r := strings.NewReplacer("n", "m", "a", "e")
fmt.Println(r.Replace("Try not to replace me"))
}

the result : http://play.golang.org/p/kW6J0GFSML
the document : http://golang.org/pkg/strings/#NewReplacer

Upvotes: 0

OneOfOne
OneOfOne

Reputation: 99224

If you're trying to replace more than one letter, then strings.Replacer is a very efficient way to go.

var r = strings.NewReplacer(
    "n", "m",
    "a", "e",
    "x", "ngma",
) // you can set it as a global variable and use it multiple times instead of creating a new one everytime. 

func main() {
    fmt.Println(r.Replace("ax is a nurderer"))
}

playground

Upvotes: 3

Salvador Dali
Salvador Dali

Reputation: 222511

How about creating a map with string_from, string_to and then applying it in a loop:

replacements := map[string]string{
    "n": "m",
    "a": "e",
}
for s_from, s_to := range(replacements){
    str = strings.Replace(str, s_from, s_to, -1)
}

this way all your rules are easily and compactly defined. And you will get something like Go Playground

Upvotes: 0

Related Questions