String 用给定单词中的适当字符替换特定字符
我想在句子中用词来改变String 用给定单词中的适当字符替换特定字符,string,replace,go,String,Replace,Go,我想在句子中用词来改变'n'与'm','a'与'e',以及10条以上的规则。目前,我正在为每个规则调用sequental way,如: word = strings.Replace(word, "n", "m", -1) word = strings.Replace(word, "a", "e", -1) .... and 10 more times 是否有更好的方法用另一个在map中给出的字符替换在Go中的字符?基本上这就是函数的用途 Map返回字符串s的一个副本,其所有字符都根据mapp
'n'与'm'
,'a'与'e'
,以及10条以上的规则。目前,我正在为每个规则调用sequental way,如:
word = strings.Replace(word, "n", "m", -1)
word = strings.Replace(word, "a", "e", -1)
.... and 10 more times
是否有更好的方法用另一个在map中给出的字符替换在Go中的字符?基本上这就是函数的用途 Map返回字符串s的一个副本,其所有字符都根据mapping函数进行了修改。如果映射返回负值,则从字符串中删除该字符,而不进行替换 示例(在上尝试): 输出:
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
}
输出是相同的()。用
string\u from
,string\u 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)
}
这样,您的所有规则都可以轻松而紧凑地定义。如果你试图替换多个字母,你会得到类似的结果,这是一种非常有效的方法
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"))
}
结果:该文件:
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"))
}
package main
import (
"fmt"
"strings"
)
func main() {
r := strings.NewReplacer("n", "m", "a", "e")
fmt.Println(r.Replace("Try not to replace me"))
}