其他分享
首页 > 其他分享> > GO语言 按照索引切割字符串并返回分割后的两个字符串

GO语言 按照索引切割字符串并返回分割后的两个字符串

作者:互联网

需求:将指定字符串按照索引切割,并将切割后的两个字符串返回

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

标签:index,string,索引,sp1,sp2,GO,str,字符串
来源: https://blog.csdn.net/qq_41629756/article/details/101198681