英文:
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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论