Summary of string cutting methods in Go programming language

  • 2020-05-30 20:23:01
  • OfStack

1.func Fields(s string) []string, this function is used to split the string by 1: n Spaces
[] string slice


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.Fields("hello widuu golang")) //out  [hello widuu golang]
}

2.func FieldsFunc(s string, f func(rune) bool) []string1


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.FieldsFunc("widuunhellonword", split)) // [widuu hello word] According to the n Character segmentation
} func split(s rune) bool {
 if s == 'n' {
  return true
 }
 return false
}

3.func Join(a []string, sep string) string, which is similar to implode in php, is a function that splits a slice of []string into a string using a delimiter


import (
 "fmt"
 "strings"
) func main() {
 s := []string{"hello", "word", "xiaowei"}
 fmt.Println(strings.Join(s, "-")) // hello-word-xiaowei
}

func Split(s, sep string) []string, join, Split this is to cut the string into slice according to the specified separator


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.Split("a,b,c,d,e", ",")) //[a b c d e]
}

5.func SplitAfter(s, sep string) []string


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.SplitAfter("a,b,c,d", ",")) //[a, b, c, d]
}

6.func SplitAfterN(s, sep string, n int) []string this function, s, returns slice of the substring after segmentation according to sep, like split1, only returns sep of the substring, if sep is empty, then every character is split


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.SplitAfterN("a,b,c,d,r", ",", 4)) //["a," "b," "c," "d,r"]
 fmt.Println(strings.SplitAfterN("a,b,c,d,r", ",", 5)) //["a," "b," "c," "d," "r"]
}

7.func SplitN(s, sep string, n int) []string, this is the length defined when cutting a string. If sep is empty, then every character is split


import (
 "fmt"
 "strings"
) func main() {
 fmt.Println(strings.SplitN("a,b,c", ",", 2)) //[a b,c]
}


Related articles: