dongmei8760 2016-03-08 22:11
浏览 6
已采纳

字符串。拆分行为很奇怪

I am doing a simple strings.Split on a date.

The format is 2015-10-04

month := strings.Split(date, "-")

output is [2015 10 03].

If I do month[0] it returns 2015 but when I do month[1], it returns

panic: runtime error: index out of range

Though it clearly isn't. Am I using it wrong? Any idea what is going on?

  • 写回答

1条回答 默认 最新

  • doucheng1944 2016-03-08 22:14
    关注

    Here's a complete working example:

    package main
    
    import "strings"
    
    func main() {
        date := "2015-01-02"
        month := strings.Split(date, "-")
        println(month[0])
        println(month[1])
        println(month[2])
    }
    

    Output:

    2015
    01
    02
    

    Playground


    Perhaps you're not using the correct "dash" character? There are lots:

    +-------+--------+----------+
    | glyph |       codes       |
    +-------+--------+----------+
    | -     | U+002D | -    |
    | ֊     | U+058A | ֊  |
    | ־     | U+05BE | ־  |
    | ᠆     | U+1806 | ᠆  |
    | ‐     | U+2010 | ‐  |
    | ‑     | U+2011 | ‑  |
    | ‒     | U+2012 | ‒  |
    | –     | U+2013 | –  |
    | —     | U+2014 | —  |
    | ―     | U+2015 | ―  |
    | ⁻     | U+207B | ⁻  |
    | ₋     | U+208B | ₋  |
    | −     | U+2212 | −  |
    | ﹘     | U+FE58 | ﹘ |
    | ﹣     | U+FE63 | ﹣ |
    | -     | U+FF0D | - |
    +-------+--------+----------+
    

    Here is the code with a different input string, which also throws an index out of bounds exception:

    package main

    import "strings"
    
    func main() {
        date := "2015‐01‐02" // U+2010 dashes
        month := strings.Split(date, "-")
        println(month[0])
        println(month[1])
        println(month[2])
    }
    

    Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?