strings.Split表现奇怪

huangapple go评论88阅读模式
英文:

strings.Split acting weird

问题

我正在对日期进行简单的字符串拆分操作。

日期的格式是 2015-10-04

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

输出结果是 [2015 10 03]

如果我使用 month[0],它会返回 2015,但是当我使用 month[1] 时,它会返回

panic: runtime error: index out of range

尽管明显不是这样。我使用方法有问题吗?你知道发生了什么吗?

英文:

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 month1, 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

得分: 7

这是一个完整的工作示例:

package main

import "strings"

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

输出结果:

2015
01
02

Playground


也许你没有使用正确的 "破折号" 字符?有很多种

+-------+--------+----------+
| 符号   | 代码   | 实体编码   |
+-------+--------+----------+
| -     | 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 | - |
+-------+--------+----------+

以下是使用不同输入字符串的代码,也会引发索引越界异常:

package main

import "strings"

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

Playground.

英文:

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.

huangapple
  • 本文由 发表于 2016年3月9日 06:11:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/35879039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定