course/test/spilt_string.go

36 lines
619 B
Go
Raw Normal View History

2024-07-14 11:08:04 +08:00
package Splitstring
import (
"strings"
)
2024-07-14 11:08:04 +08:00
//切割字符串
//example
// abc,b =>[a,c]
//func Split(str string, sep string) []string {
// tmp := make([]string, 0)
// for _, v := range str {
// if string(v) == sep {
// continue
// } else {
// tmp = append(tmp, string(v))
// }
// }
// return tmp
//}
// abc,b =>[a,c]
func Split(str string, sep string) []string {
var ret = make([]string, 0, strings.Count(str, sep)+1)
2024-07-14 11:08:04 +08:00
index := strings.Index(str, sep)
for index >= 0 {
ret = append(ret, str[:index])
str = str[index+len(sep):]
2024-07-14 11:08:04 +08:00
index = strings.Index(str, sep)
}
ret = append(ret, str)
return ret
}