MENU

Go package string

December 22, 2019 • Go

string库

Fields

var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
//定义个uint8的数组 索引分别是 \t,\n,\v,\f,\t,空格(以ascii的数字来当索引) 值都为1

func Fields(s string) []string {
    // First count the fields.
    // This is an exact count if s is ASCII, otherwise it is an approximation.
    n := 0
    wasSpace := 1
    // setBits is used to track which bits are set in the bytes of s.
    setBits := uint8(0)
        //无符号数setBits 值为0
    for i := 0; i < len(s); i++ {
        r := s[i]
        setBits |= r
        isSpace := int(asciiSpace[r])
        n += wasSpace & ^isSpace
        wasSpace = isSpace
    }

    if setBits >= utf8.RuneSelf {
        // Some runes in the input string are not ASCII.
        return FieldsFunc(s, unicode.IsSpace)
    }
    // ASCII fast path
    a := make([]string, n)
    na := 0
    fieldStart := 0
    i := 0
    // Skip spaces in the front of the input.
    for i < len(s) && asciiSpace[s[i]] != 0 {
        i++
    }
    fieldStart = i
    for i < len(s) {
        if asciiSpace[s[i]] == 0 {
            i++
            continue
        }
        a[na] = s[fieldStart:i]
        na++
        i++
        // Skip spaces in between fields.
        for i < len(s) && asciiSpace[s[i]] != 0 {
            i++
        }
        fieldStart = i
    }
    if fieldStart < len(s) { // Last field might end at EOF.
        a[na] = s[fieldStart:]
    }
    return a
}
Last Modified: March 29, 2020