起飞就起飞

golang的strings包的坑

Posted on By baixiao

strings的分割

如下strings.Split无法判断字符串中是否有某个字段,要用strings.Contains:

    
func strings_split() {
	a := ""
	needs := strings.Split(a, ",")
	fmt.Println("needs", needs, len(needs))
	for _, need := range needs {
		fmt.Println("need", need)
	}

	fmt.Println(strings.Contains(a, ","))
}

结果如下,无法通过needs的长度来判断是否包含了某个字段:

needs [] 1
need 
false

其实 Split 函数的注释写的很清楚:

// If s does not contain sep and sep is not empty, Split returns a
// slice of length 1 whose only element is s.

strings的剪切

如下strings.TrimLeft无法切断某一个字符串,要用strings.TrimPrefix:

    
func strings_TrimLeft() {
	a := "not enough arguments in call to route.MergeGpsRouteSummary"
	fmt.Println(strings.TrimLeft(a, "not enough arguments in call to "))
}

结果如下:

.MergeGpsRouteSummary