golang字符串常用操作
获取字符串的长度
package main import ( "fmt" ) var name string = "helloworld" func main() { fmt.Println(len(name )) }
字符串拼接
func main() { info := name + fmt.Sprintf(" %d", age) fmt.Println(info) }
字符串切割
var name string = "helloworld" func main() {
info := strings.Split(name, "ll")
fmt.Println(info)
}
判断是否包含
var name string = "helloworld" func main() { if strings.Contains(name, "h") { fmt.Println("Contains") } }
判断前缀后缀
var name string = "helloworld" func main() { fmt.Println(strings.HasPrefix(name, "h")) fmt.Println(strings.HasSuffix(name, "d")) }
判断字符出现的索引位置
var name string = "helloworld" func main() { fmt.Println(strings.Index(name, "l")) fmt.Println(strings.LastIndex(name, "l"))
}
切片元素拼接字符串
var name string = "helloworld" func main() { nameList := make([]string, 0) nameList = append(nameList, name) nameList = append(nameList, name) fmt.Println(strings.Join(nameList, ",")) }
字符串转义符
Go 语言的字符串常见转义符包含回车、换行、单双引号、制表符等,如下表所示。
\r 回车符
\n 换行
\t 制表符
\\ 反斜杠
Welcome to visit