首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >替换golang中出现的第N个字符串

替换golang中出现的第N个字符串
EN

Stack Overflow用户
提问于 2017-05-24 04:43:17
回答 3查看 6.3K关注 0票数 5

如何替换在golang中出现的字符串的第n次(在本例中是第二次)?下面的代码将示例字符串optimismo from optimism替换为o from optimism,而我希望它为optimismo from

代码语言:javascript
复制
package main

import (
    "fmt"
    "strings"
)

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-05-24 06:37:31

例如,

代码语言:javascript
复制
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)
}

输出:

代码语言:javascript
复制
"optimismo from optimism"
"optimismo from "
票数 6
EN

Stack Overflow用户

发布于 2019-03-05 04:35:09

对于任何偶然发现这篇文章并希望替换上一篇文章的人

代码语言:javascript
复制
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)
}
票数 8
EN

Stack Overflow用户

发布于 2017-05-24 04:54:08

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

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

代码语言:javascript
复制
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)
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44144641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档