substring方法的几种实现
- 原生方法,直接使用slice切片实现,但此方法对于包括中文字符就截取错误
s:="abcde"
fmt.Println(s[0:2]);
//输出
//ab
//包含中文的字符串
s2 := "我是中国人"
fmt.Println(s2[0:2])
//输出
// ��
//有乱码呀
rune
//获取source的子串,如果start小于0或者end大于source长度则返回""
//start:开始index,从0开始,包括0
//end:结束index,以end结束,但不包括end
func substring(source string, start int, end int) string {
var r = []rune(source)
length := len(r)
if start < 0 || end > length || start > end {
return ""
}
if start == 0 && end == length {
return source
}
return string(r[start : end])
}
rune
//获取source的子串,如果start小于0或者end大于source长度则返回""
//start:开始index,从0开始,包括0
//end:结束index,以end结束,但不包括end
func substring(source string, start int, end int) string {
var r = []rune(source)
length := len(r)
if start < 0 || end > length || start > end {
return ""
}
if start == 0 && end == length {
return source
}
if start == end {
return string(r[start])
}
var substring = ""
for i := 0; i < length; i++ {
if i < start {
continue
}
if i >= end {
break
}
substring += string(r[i])
}
return substring
}
//方法二:
func substring(source string, start int, end int) string {
var substring = ""
var pos = 0
for _, c := range source {
if pos < start {
pos++
continue
}
if pos >= end {
break
}
pos++
substring += string(c)
}
return substring
}
//方法三
func substring(source string, start int, end int) string {
var r = []rune(source)
length := len(r)
if start < 0 || end > length || start > end {
return ""
}
if start == 0 && end == length {
return source
}
var substring = ""
for i := start; i < length; i++ {
substring += string(r[i])
}
return substring
}
s := "1人民币哈哈只"
fmt.Printf("%s\n", substring(s, 1, 7))
//输出
//人民币哈哈只