为什么将字符串按其自身进行分割会返回一个长度为2的空切片?

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

Why does splitting a string on itself return an empty slice with a length of two?

问题

我正在编写一个程序,可能会在字符串本身上进行拆分。字符串是一个URL,我想按斜杠进行拆分。我想根据URL字符串执行不同的操作。

我更加好奇的是为什么strings.Split返回那个意外的切片。我尝试在Python中进行这个操作,发现它也返回一个长度为2的列表。对我来说,直觉上应该返回一个空列表(切片/数组)。为什么会返回两个空字符串呢?有没有一个很好的原因?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Split("/", "/"))
    fmt.Println("len:", len(strings.Split("/", "/")))
}

输出结果为:

[ ]
len: 2

http://play.golang.org/p/-lYrmAKOMR

英文:

I'm writing a program where I might end up splitting a string on itself. The string is a URL and I want to split on the slash. I want to do different things based on the URL string.

I'm more curious about why strings.Split returns that unexpected slice. I tried doing this in Python and noticed it also returns a list with a length of two. The intuitive thing for me seems to return an empty list (slice/array). Is there a good reason why two empty strings are returned instead?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Split("/", "/"))
    fmt.Println("len:", len(strings.Split("/", "/")))
}

// Prints this
[ ]
len: 2

http://play.golang.org/p/-lYrmAKOMR

答案1

得分: 13

据我理解,split函数返回斜杠/之前的所有内容(即空),作为第一个元素,以及斜杠/之后的所有内容(同样为空),作为第二个元素。因此,得到了两个空字符串。至于为什么会得到空字符串,这是为了使split()函数可以与join函数相反,具体解释可以参考这里:

https://stackoverflow.com/questions/2197451/why-are-empty-strings-returned-in-split-results

英文:

As I understand it, the split function returns everything before the / (which is nothing) in the first item, and everything after the / (also nothing) in the second item. Hence, two empty strings. As for why you ever get empty strings, it's so that split() can basically be the opposite of join, as explained here:

https://stackoverflow.com/questions/2197451/why-are-empty-strings-returned-in-split-results

huangapple
  • 本文由 发表于 2014年7月19日 07:50:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/24835321.html
匿名

发表评论

匿名网友

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

确定