猿问

如何根据 Go 中第二次出现的分隔符拆分字符串?

我有一个字符串a_b_c_d_e。我想将它拆分为a_band c_d_e。这样做的好方法是什么?

目前我知道如何使用 SplitN 函数根据第一个下划线拆分字符串:

strings.SplitN(str, "_", 2)

如果 str 是a_b_c_d_e那么输出将是aand b_c_d_e


心有法竹
浏览 167回答 2
2回答

当年话下

你想要的东西不存在,据我所知。所以你只需要自己做:package hellofunc split(s string, sep rune, n int) (string, string) {   for i, sep2 := range s {      if sep2 == sep {         n--         if n == 0 {            return s[:i], s[i+1:]         }      }   }   return s, ""}

拉莫斯之舞

我有一个字符串a_b_c_d_e。我想将它拆分为a_band c_d_e。包中strings有一个Cut函数// 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.将函数的代码分叉Cut为Cut2package mainimport (    "fmt"    "strings")// Cut2 slices s around the second instance of sep,// returning the text before and after sep.// The found result reports whether sep appears twice in s.// If sep does not appear twice in s, Cut2 returns s, "", false.func Cut2(s, sep string) (before, after string, found bool) {    if i := strings.Index(s, sep); i >= 0 {        i += len(sep)        if j := strings.Index(s[i:], sep); j >= 0 {            i += j            return s[:i], s[i+len(sep):], true        }    }    return s, "", false}func main() {    s := "a_b_c_d_e"    fmt.Println(s)    fmt.Println(Cut2(s, "_"))}https://go.dev/play/p/6-OBBU70snQa_b_c_d_ea_b c_d_e true
随时随地看视频慕课网APP

相关分类

Go
我要回答