【问题标题】:How to swap substrings of a string in golang?如何在golang中交换字符串的子字符串?
【发布时间】: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

如果有多种方法可以做到这一点,我会很高兴了解每种方法的优缺点。

【问题讨论】:

    标签: string go swap


    【解决方案1】:

    strings.ReplaceAll() 不执行“切换”,它只是将出现的 some 字符串替换为 another;但它不会执行用 some 替换 another。意思是ReplaceAll(s, "a", "b") 将用"b" 替换所有出现的"a",但它不会用"a" 替换出现的"b"

    这是 2 次替换操作。而且这两个替换操作不能按顺序执行,因为一旦将“apple”替换为“mango”,您将只有“mango”,因此如果将“mango”替换为“apple” s,你只剩下“苹果”了。

    相反,您可以使用strings.Replacer 列出多个可替换对,其Replacer.Replace() 方法将在一个步骤中执行所有替换。

    还请注意,您不应将所有“a”替换为“an”,因为您的输入中可能还有其他“a”,而不仅仅是在“mango”之前。因此,最好将“an apple”替换为“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", "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
    

    【讨论】:

    • 你能详细说明你第一句话的意思吗?另外,如果 r.WriteString(w, s) 是 r.Replace(s) + write_to_file 的简写,还是有什么不同?
    • @muruDiaz 查看已编辑的答案。是的,Replacer.WriteString() 执行r.Replace(s) 并将结果写入w,但它比这两个顺序执行的步骤更有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2017-10-23
    • 2014-12-17
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多