一、golang的字符串长度
1. len()内置系统函数,计算字符串结果是字符串的字节长度,不是字符长度
//1.ASCII字符串长度(字节长度)
str1 := "wo ai zhong guo"
fmt.Println(len(str1)) //15
//2.带中文的字符串长度(字节长度)
str2 := "我爱中国"
fmt.Println(len(str2)) //12 4 * 3字节 = 12字节
2. 计算带中文的字符串长度。 需要将字符串转为 rune类型(int32)
//带中文的字符串长度
str1 := "wo ai 中国"
r := []rune(str1)
fmt.Println(len(r)) //8
//也可以使用 utf8.RuneCountInString() 计算携带中文的字符串长度
num := utf8.RuneCountInString(str1)
fmt.Println(num) //8
3.为什么字符串带中文,字符长度计算方式不一样?
因为golang默认的字符编码是utf-8, 字符串的底层是 []byte类型,英文及标点符号都是每个占1个字节,中文占3个字节。 len() 函数实际上计算的是 字符串的字节长度。要计算中文长度,那么就得转成rune 或者 通过 utf8.RuneCountInString(str) 来计算。文章来源:https://www.toymoban.com/news/detail-620254.html
二、字符串分割成切片,切片拼接成字符串
//字符串分割
str1 := "刘备,关羽,张飞"
s := strings.Split(str1, ",")
fmt.Println(s) //切片 [刘备 关羽 张飞]
//切片拼接成字符串
str2 := strings.Join(s, "-")
fmt.Println(str2) //字符串 刘备-关羽-张飞
三、字符串查找(字符串中是否存在某些子串)
//1.字符串中是否存在某些字符
str := "http://baidu.com/index/index.html"
b := strings.Contains(str, "http://") //字符串中是否存在 http头
fmt.Println(b) //true
//2.某个子串 在字符串中有多少个
count := strings.Count(str, "index")
fmt.Println(count) //2
//3.字串在字符串中开始索引位置
index := strings.Index(str, "bai")
fmt.Println(index) //7
//4.字串在字符串中最后一次索引位置
index = strings.LastIndex(str, "index")
fmt.Println(index) //23
四、剔除字符串左右空格及左右指定字符
//1.字符串去左右空格
str1 := " 野蛮生长 "
fmt.Println(utf8.RuneCountInString(str1)) //字符长度6
str := strings.TrimSpace(str1)
fmt.Println(str)
fmt.Println(utf8.RuneCountInString(str)) //字符长度4 去掉了左右空格
//2.去掉左右指定字符
str2 := "-野蛮生长-"
str = strings.Trim(str2, "-")
fmt.Println(str) //野蛮生长
//3.去掉左侧指定字符
str3 := "-野蛮生长-"
str = strings.TrimLeft(str3, "-")
fmt.Println(str) //野蛮生长-
//4.去掉右侧指定字符
str4 := "-野蛮生长-"
str = strings.TrimRight(str4, "-")
fmt.Println(str) //-野蛮生长
五、字符串中的某些字符替换
//1.字符串中某个字符替换掉
str := "123 + 456 + 789 = ?"
str1 := strings.Replace(str, "+", "-", 1) //替换掉一个
fmt.Println(str1) //123 - 456 + 789 = ?
str2 := strings.Replace(str, "+", "-", 2) //替换掉两个
fmt.Println(str2) //123 - 456 - 789 = ?
str3 := strings.ReplaceAll(str, "+", "-") //替换掉所有
fmt.Println(str3) //123 - 456 - 789 = ?
六、数字字符串转数字(int),int转数字字符串文章来源地址https://www.toymoban.com/news/detail-620254.html
//1.数字字符串转int
str1 := "123789ab"
number1, _ := strconv.Atoi(str1)
fmt.Println(number1) //0
str2 := "123789"
number2, _ := strconv.Atoi(str2)
fmt.Println(number2) //123789
//2.int转字符串
number := 123456
str := strconv.Itoa(number)
fmt.Println(str) //123789
fmt.Println(reflect.TypeOf(str)) //string
到了这里,关于golang 字符串操作、处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!