Regardless of the development language, the split function is often used. Recently discovered the split function in the strings bag has a pit, really live long see.
package mainimport "fmt"import "strings"func main() { str := "" v := strings.Split(str, "#") if len(v)%2 != 0 { fmt.Printf("v len is [%d]", len(v)) }}
Expect to get the result should be 0, because often read the data field when it will do is not a few tuples of judgment. The actual output is:
v len is [1]
See the implementation of split
func genSplit(s, sep string, sepSave, n int) []string { if n == 0 { return nil } if sep == "" { return explode(s, n) } if n < 0 { n = Count(s, sep) + 1 } c := sep[0] start := 0 a := make([]string, n) na := 0 for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) { a[na] = s[start : i+sepSave] na++ start = i + len(sep) i += len(sep) - 1 } } a[na] = s[start:] return a[0 : na+1]}
You can see that the last returned slice has at least one value. Pay more attention to details, not to use the inherent concept of new things.