在golang中替换第N个字符串

时间:2017-05-23 20:43:17

标签: string go

如何在golang中替换第n个(在本例中为第二个)字符串的出现?当我想要optimismo from optimism时,以下代码将示例字符串o from optimism替换为optimismo from

package main

import (
    "fmt"
    "strings"
)

func main() {
    mystring := "optimismo from optimism"
    excludingSecond := strings.Replace(mystring, "optimism", "", 1)
    fmt.Println(excludingSecond)
}

3 个答案:

答案 0 :(得分:4)

例如,

package main

import (
    "fmt"
    "strings"
)

// Replace the nth occurrence of old in s by new.
func replaceNth(s, old, new string, n int) string {
    i := 0
    for m := 1; m <= n; m++ {
        x := strings.Index(s[i:], old)
        if x < 0 {
            break
        }
        i += x
        if m == n {
            return s[:i] + new + s[i+len(old):]
        }
        i += len(old)
    }
    return s
}

func main() {
    s := "optimismo from optimism"
    fmt.Printf("%q\n", s)
    t := replaceNth(s, "optimism", "", 2)
    fmt.Printf("%q\n", t)
}

输出:

"optimismo from optimism"
"optimismo from "

答案 1 :(得分:2)

如果你总是知道会有两个,你可以使用https://godoc.org/strings#Index找到第一个的索引,然后对所有内容进行替换,最后将它们组合在一起。

https://play.golang.org/p/CeJFViNjgH

func main() {
    search := "optimism"
    mystring := "optimismo from optimism"

    // find index of the first and add the length to get the end of the word
    ind := strings.Index(mystring, search)
    if ind == -1 {
        fmt.Println("doesn't exist")
        return // error case
    }
    ind += len(search)

    excludingSecond := mystring[:ind]

    // run replace on everything after the first one
    excludingSecond += strings.Replace(mystring[ind:], search, "", 1)
    fmt.Println(excludingSecond)
}

答案 2 :(得分:0)

对于在这篇文章上绊脚石并希望替换上一次出现的人

package main

import (
    "fmt"
    "strings"
)

func main() {
    mystring := "optimismo from optimism"

    i := strings.LastIndex(mystring, "optimism")
    excludingLast := mystring[:i] + strings.Replace(mystring[i:], "optimism", "", 1)
    fmt.Println(excludingLast)
}