亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何刪除字符串模式和該模式后面的所有字符串?

如何刪除字符串模式和該模式后面的所有字符串?

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條經驗 獲得超8個贊

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 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號