php editor Xinyi brings an idiomatic method of iterating a string and replacing the values in the original string with the mapped value. This method can help developers simplify the string operation process and improve development efficiency. By using a mapped array, developers can define a set of key-value pairs and then use an iterative method to replace specific values in the original string with mapped values. This method is not only simple and easy to understand, but also can be applied to various scenarios, such as data processing, text replacement, etc. Both beginners and experienced developers can benefit from this approach to handle string operations quickly and efficiently.
I have a working solution about iterating a string and mapping rune
to a 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)) }
This suits my wishes... but I'm curious about a cleaner way (if possible) rather than allocating a whole new string to build from the original string. If I could modify the original content in-place while iterating, I would prefer to do so.
This is the playground
Use strings.Replacer to replace strings.
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) }
//m.sbmmt.com/link/7d420e2b2939762031eed0447a9be19f
The above is the detailed content of Idiomatic way to iterate over a string and replace values in the original string with mapped values. For more information, please follow other related articles on the PHP Chinese website!