The pit of the split function inside the strings bag

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.