0.字符串为不可变类型,内部使用指针指向UTF-8字节数组
不过要修改字符串可以先将其转换成[]byte或者[]rune。如下
package main func main() { s := "abcd" bs := []byte(s) bs[1] = ‘B‘ println(string(bs)) u := "电脑" us := []rune(u) us[1] = ‘话‘ println(string(us)) }
输出:
aBcd
电话
for遍历字符串有byte和rune两种方式,见代码
package main import ( "fmt" ) func main() { s := "abc汉字" for i := 0; i < len(s); i++ { // byte fmt.Printf("%c,", s[i]) } fmt.Println() for _, r := range s { // rune fmt.Printf("%c,", r) } fmt.Println() }
输出
a,b,c,æ,±,?,å,,?, a,b,c,汉,字,
一些常用接口
1.判断是不是以某个字符串开头
package main import ( "fmt" "strings" ) func main() { str := "hello world" res0 := strings.HasPrefix(str, "http://") res1 := strings.HasPrefix(str, "hello") fmt.Printf("res0 is %v\n", res0) fmt.Printf("res1 is %v\n", res1) }
输出
res0 is false res1 is true
源码片段
// HasPrefix tests whether the string s begins with prefix. func HasPrefix(s, prefix string) bool { return len(s) >= len(prefix) && s[0:len(prefix)] == prefix }
2.判断是不是以某个字符串结尾
package main import ( "fmt" "strings" ) func main() { str := "hello world" res0 := strings.HasSuffix(str, "http://") res1 := strings.HasSuffix(str, "world") fmt.Printf("res0 is %v\n", res0) fmt.Printf("res1 is %v\n", res1) }
输出
res0 is false res1 is true
源码片段
// HasSuffix tests whether the string s ends with suffix. func HasSuffix(s, suffix string) bool { return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix }
待续...
原文地址:https://www.cnblogs.com/chenguifeng/p/11780416.html
时间: 2024-11-02 20:45:48