Golang中字符串处理主要用的是Strings包
1、Index(s string, str string) int
:返回子串str在字符串s中第一次出现的位置。如果找不到则返回-1;如果str为空,则返回0
例:
a := "in"
b := "I an in China"
c := strings.Index(b, a)
fmt.Println(c) //结果: 5
2、LastIndex(s string, str string) int
: 返回子串str在字符串s中最后一次出现的位置。如果找不到则返回-1;如果str为空则返回字符串s的长度。
例:
string := "in"
s := "I an in China
c := strings.LastIndex(s, string)
fmt.Println(c) //返回 10
3、IndexRune(s string, r rune) int :返回字符r在字符串s中第一次出现的位置。如果找不到则返回-1
string := 'i'
s := "I am in China"
c := strings.IndexRune(s, rune(string))
fmt.Println(c) //结果: 5
注意: strings.IndexRune区分大小写,rune里的定界符必须用单引号
4、Contains(s string, str string) bool:判断字符串s中是否包含个子串str。包含或者str为空则返回true。
string := "i"
s := "I am in China"
c := strings.Contains(s, string)
fmt.Println(c) //结果: true
5、HasPrefix(s string, prefix string) bool:判断字符串s是否以prefix开头。
string := "I"
s := "I am in China"
c := strings.HasPrefix(s, string)
fmt.Println(c) //结果:trur
6、HasSuffix(s, suffix string) bool :判断字符串s是否以prefix结尾。
string = "I"
s = "I am in China"
c = strings.HasSuffix(s, string)
fmt.Println(c) //结果:false
7、Replace(s, old, new string, n int) string:返回s的副本,并将副本中的old字符串替换为new字符串,替换次数为n次,如果n为-1,则全部替换;如果 old 为空,则在副本的每个字符之间都插入一个new
s := "I am in China"
d := strings.Replace(s, "a", "f", -1)
fmt.Println(d)
8、ToLower(s string) string:将s中的所有字符修改为其小写格式。对于非ASCII字符,它的小写格式需要查表转换。
9、ToUpper(s string) string:将s中的所有字符修改为其大写格式。对于非ASCII字符,它的大写格式需要查表转换。
10、Trim(s string, str string) string:删除s首尾连续的包含在str中的字符。
11、TrimLeft(s string, str string) string:删除s头部连续的包含在str中的字符串。
12、TrimRight(s string, str string) string:删除s尾部连续的包含在str中的字符串。
13、TrimSpace(s string) string:删除s首尾连续的的空白字符。
14、Repeat(s string, n int) string:将n个字符串s连接成一个新的字符串。
15、Split(s, str string) []string:以str为分隔符,将s切分成多个子切片,结果中**不包含**str本身。如果str为空,则将s切分成Unicode字符列表。如果s中没有str子串,则将整个s作为[]string的第一个元素返回。
s := "I am in China" d := strings.Split(s, " ") fmt.Println(d) //结果: [I am in China]
16、字符串转 []byte:
var bytes = []byte("hello go") fmt.Println(bytes) //结果:[104 101 108 108 111 32 103 111]
17、 []byte 转字符串:
str := string([]byte{97, 98, 99})
fmt.Println(str) //结果: abc