如何解决如何在golang中交换字符串的子字符串?
我正在尝试学习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()。
例如:
苹果->芒果
芒果->苹果
a-> an
an-> a
所需的输出:
I have a mango but not an apple,and she has an apple but not a mango
如果有多种方法,我将很高兴了解每种方法的优缺点。
解决方法
strings.ReplaceAll()
不执行“切换”,只是将 some 字符串的出现替换为另一个;但不会执行将另一个替换为 some 。意味着ReplaceAll(s,"a","b")
将所有出现的"a"
替换为"b"
,但不会替换"b"
的出现"a"
。
这是2个替换操作。并且这2个替换操作无法顺序执行,因为一旦将“ apple”替换为“ mango”,您将只有“ mango”,因此如果要用“ apple”替换“ mango” s,只剩下“苹果”。
相反,您可以使用strings.Replacer
在其中列出多个可替换对,并且其Replacer.Replace()
方法将一步执行所有替换。
还请注意,您不应将所有“ a”替换为“ an”,因为输入中可能会存在其他“ a”,而不仅仅是“ mango”之前。最好是用“芒果”代替“苹果”,反之亦然。
s := "I have an apple but not a mango,and she has a mango but not an apple"
fmt.Println(s)
r := strings.NewReplacer("an apple","a mango","an apple")
s = r.Replace(s)
fmt.Println(s)
输出(在Go Playground上尝试):
I have an apple but not a mango,and she has a mango but not an apple
I have a mango but not an apple,and she has an apple but not a mango
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。