为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除字符串模式和该模式后面的所有字符串?

如何删除字符串模式和该模式后面的所有字符串?

Go
明月笑刀无情 2022-12-19 10:42:15
例如 :package mainimport "fmt"func main() {    pattern := "helloworld."    myString := "foo.bar.helloworld.qwerty.zxc.helloworld.asd"    fmt.Println(removeFromPattern(pattern, myString))}func removeFromPattern(p, ms string) string {    // I confused here (in efficient way)}想要的输出:qwerty.zxc.helloworld.asd我如何获得想要的输出,以及如何从中删除该pattern模式后面的第一个和所有字符串myString?
查看完整描述

3 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

1-使用_, after, _ = strings.Cut(ms, p),试试这个:


func removeFromPattern(p, ms string) (after string) {

    _, after, _ = strings.Cut(ms, p) // before and after sep.

    return

}

哪个用途strings.Index:


// Cut slices s around the first instance of sep,

// returning the text before and after sep.

// The found result reports whether sep appears in s.

// If sep does not appear in s, cut returns s, "", false.

func Cut(s, sep string) (before, after string, found bool) {

    if i := Index(s, sep); i >= 0 {

        return s[:i], s[i+len(sep):], true

    }

    return s, "", false

}

2-使用strings.Index,试试这个:


func removeFromPattern(p, ms string) string {

    i := strings.Index(ms, p)

    if i == -1 {

        return ""

    }

    return ms[i+len(p):]

}

3-使用strings.Split,试试这个:


func removeFromPattern(p, ms string) string {

    a := strings.Split(ms, p)

    if len(a) != 2 {

        return ""

    }

    return a[1]

}

4-使用regexp,试试这个


func removeFromPattern(p, ms string) string {

    a := regexp.MustCompile(p).FindStringSubmatch(ms)

    if len(a) < 2 {

        return ""

    }

    return a[1]

}


查看完整回答
反对 回复 2022-12-19
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

strings.Split就够了


func main() {

    pattern := "helloworld."

    myString := "foo.bar.helloworld.qwerty.zxc"


    res := removeFromPattern(pattern, myString)

    fmt.Println(res)

}


func removeFromPattern(p, ms string) string {

    parts := strings.Split(ms, p)

    if len(parts) > 1 {

        return parts[1]

    }

    return ""

}


查看完整回答
反对 回复 2022-12-19
?
潇湘沐

TA贡献1816条经验 获得超6个赞

func removeFromPattern(p, ms string) string {

    return strings.ReplaceAll(ms, p, "")

}

func main() {

    pattern := "helloworld."

    myString := "foo.bar.helloworld.qwerty.zxc"

    res := removeFromPattern(pattern, myString)

    fmt.Println(res)

}


查看完整回答
反对 回复 2022-12-19
  • 3 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号