Home > Back-end >  How to split a string based on second occurence of delimiter in Go?
How to split a string based on second occurence of delimiter in Go?

Time:10-02

I have a string a_b_c_d_e. I want to split it as a_b and c_d_e. What would be a good a way to do it?

Currently I know how to split a string based on first underscore by using the SplitN function:

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

If str is a_b_c_d_e then output will be a and b_c_d_e.

CodePudding user response:

What you want doesn't exist, that I know of. So you just need to make your own:

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

CodePudding user response:

I have a string a_b_c_d_e. I want to split it as a_b and c_d_e.


In the strings package there is a Cut function

// 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.

Fork the code for the Cut function as 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
  • Related