将给定单词中的特定字符替换为适当的字符。

huangapple go评论74阅读模式
英文:

Replace specific characters with appropriate characters in given word

问题

在Go语言中,你可以使用strings.NewReplacer函数来实现更高效的字符替换。你可以创建一个strings.Replacer对象,将需要替换的字符和对应的替换字符传递给它,然后使用Replace方法进行替换操作。以下是一个示例代码:

replacer := strings.NewReplacer(
    "n", "m",
    "a", "e",
    // 添加更多的替换规则
)

word = replacer.Replace(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?

答案1

得分: 5

基本上,strings.Map() 函数的作用是将字符串 s 的所有字符根据映射函数进行修改并返回副本。如果映射函数返回一个负值,则该字符将从字符串中删除而不进行替换。

示例(在 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
    }
}

输出结果:

Try mot to replece me

使用映射

如果有多个规则,可以简化这段代码:

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

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

输出结果与前面相同(Go Playground)。

英文:

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).

答案2

得分: 3

如果你想替换多个字母,那么strings.Replacer是一种非常高效的方法。

var r = strings.NewReplacer(
    "n", "m",
    "a", "e",
    "x", "ngma",
) // 你可以将其设置为全局变量,并在多个地方重复使用,而不是每次都创建一个新的实例。

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

playground

英文:

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"))
}

<kbd>playground</kbd>

答案3

得分: 0

如何创建一个带有string_fromstring_to的映射,并在循环中应用它:

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

这样,你可以轻松而简洁地定义所有的规则。你将得到类似于<kbd>[Go Playground][1]</kbd>的结果。

英文:

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

replacements := map[string]string{
	&quot;n&quot;: &quot;m&quot;,
	&quot;a&quot;: &quot;e&quot;,
}
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 <kbd>Go Playground</kbd>

答案4

得分: 0

package main
import (
    "fmt"
    "strings"
)

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

结果:http://play.golang.org/p/kW6J0GFSML
文档:http://golang.org/pkg/strings/#NewReplacer

英文:
package main
import (
    &quot;fmt&quot;
    &quot;strings&quot;
)

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

the result : http://play.golang.org/p/kW6J0GFSML&lt;br>
the document : http://golang.org/pkg/strings/#NewReplacer

huangapple
  • 本文由 发表于 2015年5月19日 06:39:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/30313912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定