Go语言 迭代字符串并将原始字符串中的值替换为Map值的惯用方法

z9smfwbn  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(106)

我有一个工作解决方案来迭代字符串并将runeMap到一个Map

package main

import (
    "fmt"
)

func main() {

    numToString := map[rune]string{
        '0': "zero",
        '1': "one",
        '2': "two",
        '3': "three",
        '4': "four",
        '5': "five",
        '6': "six",
        '7': "seven",
        '8': "eight",
        '9': "nine",
    }

    testStr := "one two 3 four"
    newStr := ""
    for _, char := range testStr {
        if val, ok := numToString[char]; ok {
            newStr += val
            continue
        }
        newStr += string(char)
    }
    // prints one two three four
    fmt.Println(string(newStr))
}

这就是我想要的。然而,我对一种更干净的方式(如果可能的话)感到好奇,而不是分配一个全新的字符串来基于原始字符串进行构建。如果我可以在迭代时修改原始代码,我会更喜欢这样。
Playgroundhere

tquggr8v

tquggr8v1#

使用字符串。替换器来替换字符串。

var numToString = strings.NewReplacer(
    "0", "zero",
    "1", "one",
    "2", "two",
    "3", "three",
    "4", "four",
    "5", "five",
    "6", "six",
    "7", "seven",
    "8", "eight",
    "9", "nine").Replace

func main() {
    testStr := "one two 3 four"
    newStr := numToString(testStr)
    fmt.Println(newStr)
}

https://go.dev/play/p/hhLC2N6064P

相关问题