【发布时间】:2020-08-14 07:49:25
【问题描述】:
我正在尝试学习 Go-lang,因此在 Go 中使用字符串。但我无法正确交换字符串中的子字符串。
我的代码是:
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "I have an apple but not a mango, and she has a mango but not an apple"
fmt.Println(mystr)
mystr = strings.ReplaceAll(mystr, "apple", "(apple)")
mystr = strings.ReplaceAll(mystr, "mango", "apple")
mystr = strings.ReplaceAll(mystr, "(apple)", "mango")
fmt.Println(mystr)
mystr = strings.ReplaceAll(mystr, "an", "(a)")
mystr = strings.ReplaceAll(mystr, "a", "an")
mystr = strings.ReplaceAll(mystr, "(an)", "a")
fmt.Println(mystr)
}
输出:
I have an apple but not a mango, and she has a mango but not an apple
I have an mango but not a apple, and she has a apple but not an mango
I hanve a mago but not an anpple, ad she hans an anpple but not a mago
有没有办法输入列表或字典(如在 python 中),这样我就可以定义交换并且不需要多次使用 strings.ReplaceAll()。
例如:
苹果 -> 芒果
芒果->苹果
一个->一个
一个->一个
期望的输出:
I have a mango but not an apple, and she has an apple but not a mango
如果有多种方法可以做到这一点,我会很高兴了解每种方法的优缺点。
【问题讨论】: