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

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

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

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

Go
心有法竹 2023-02-21 16:32:55
我有一個字符串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。
查看完整描述

2 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

你想要的東西不存在,據我所知。所以你只需要自己做:


package hello


func 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, ""

}


查看完整回答
反對 回復 2023-02-21
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

我有一個字符串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為Cut2


package main


import (

    "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-OBBU70snQ


a_b_c_d_e

a_b c_d_e true


查看完整回答
反對 回復 2023-02-21
  • 2 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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