golang学习笔记第二部分:7.字符串常用函数
14、字符串常用函数
- 统计字符串长度,按字节返回 len(str)
- 字符串遍历,同时处理有中文的问题 r := []rune(str)
- 字符串转整数 n,err := strconv.Atoi(“123”)
- 整数转字符串 str := strconv.Itoa(123) //注意,这里只返回一个结果
- 字符串转[]byte var bytes := []byte(“hello go”)
- []byte转字符串 str4 := string([]byte{104, 101, 108, 108, 111, 32, 103, 111})
- 十进制转2,8,16进制 str := strconv.FormatInt(123,2)
- 查找子串是否在指定的字符串中 res := strings.Contains(“hello go”, “go”)
- 统计一个字符串有几个指定的字串 num := strings.Count(“hello”, “l”)
- 不区分大小写的字符串比较(==是区分字母大小写的比较)fmt.Println(strings.EqualFold(“abc”, “AbC”))
- 返回子串在字符串第一次出现的index值,如果没有返回-1 strings.Index(“abc_STRING_abc”, “abc”)
- 返回子串在字符串最后一次出现的index值,如果没有返回-1 strings.LastIndex(“abc_STRING_abc”, “abc”)
- 将指定的子串替换成另外一个子串 strings.Replace(“go go hello”, “go”, “go语言”, n) n为要替换的数量,-1为全部
- 按照指定的某个字符,为分割标识,将一个字符串拆分成字符串数组 strings.Split(“a,b,c”,",")
- 将字符串的字母进行大小写转换 strings.ToLower(“abc”) ToUpper
- 将字符串左右两边的空格去掉 strings.TrimSpace(" hei joy ")
- 将字符串左右两边的指定的字符去掉 strings.Trim("!hello!")
- 将字符串左/右的指定的字符去掉 strings.TrimLeft("!hello","!") strings.TrimRight(“hello!”,"!")
- 判断字符串是否以指定的字符串开头:strings.HasPrefix(“http://xxx.xxx.com”,“http”)
- 判断字符串是否以指定的字符串结尾:strings.HasSuffix(“http://xxx.xxx.com”,“com”)
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
str := "hello长沙"
fmt.Println("str len = ", len(str))
str2 := []rune(str)
for i := 0; i < len(str2); i++ {
fmt.Printf("字符=%c\n", str2[i])
}
n, err := strconv.Atoi("112233")
if err != nil {
fmt.Println("转换错误", err)
} else {
fmt.Println("转换结果", n)
}
str3 := strconv.Itoa(123)
fmt.Printf("res=%v, str3=%T\n", str3, str3)
var bytes = []byte("hello go")
fmt.Printf("res=%v, tytes=%T\n", bytes, bytes)
str4 := string([]byte{104, 101, 108, 108, 111, 32, 103, 111})
fmt.Printf("res=%v, tytes=%T\n", str4, str4)
str5 := strconv.FormatInt(123, 2)
fmt.Printf("res=%v, tytes=%T\n", str5, str5)
res := strings.Contains("hello go", "go")
fmt.Printf("res=%v, tytes=%T\n", res, res)
num := strings.Count("hello", "l")
fmt.Printf("res=%v, tytes=%T\n", num, num)
fmt.Println(strings.EqualFold("abc", "AbC"))
fmt.Println(strings.Index("abc_STRING_abc", "abc"))
fmt.Println(strings.LastIndex("abc_STRING_abc", "abc"))
fmt.Println(strings.Replace("go go hello", "go", "go语言", -1))
fmt.Println(strings.Split("a,b,c", ","))
fmt.Println(strings.ToUpper("asdfDFG"))
fmt.Println(strings.Trim("!hello!", "!"))
fmt.Println(strings.HasPrefix("http://xxx.xxx.com", "http"))
}