需求:将指定字符串按照索引切割,并将切割后的两个字符串返回
package main
import (
"fmt"
)
func main() {
rawString := "HelloWorld"
index := 3
sp1, sp2 := splitStringbyIndex(rawString, index)
fmt.Printf("The string %s split at position %d is: %s / %s\n", rawString, index, sp1, sp2)
}
func splitStringbyIndex(str string, i int) (sp1, sp2 string) {
// 优化,优先操作二进制数据
rawStrSlice := []byte(str)
sp1 = string(rawStrSlice[:i])
sp2 = string(rawStrSlice[i:])
// 直接操作字符串也可以
//sp1 = str[:i]
//sp2 = str[i:]
return
}
结果:
The string HelloWorld split at position 3 is: Hel / loWorld