登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-03-07 19:54:27 191浏览 收藏

哈喽!今天心血来潮给大家带来了《如何在Go中根据第二次出现的分隔符来拆分字符串?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我有一个字符串 a_b_c_d_e。我想将其拆分为 a_bc_d_e。有什么好的方法可以做到这一点?

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

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

如果 str 为 a_b_c_d_e,则输出将为 ab_c_d_e


正确答案


据我所知,你想要的东西并不存在。所以你只需要自己制作:

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

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>