Golang(Go语言)代码技巧之字符串(string)

前端之家收集整理的这篇文章主要介绍了Golang(Go语言)代码技巧之字符串(string)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  • 改变字符串中的某些字符
  
  
str := "hello roc"bytes []byte(str)bytes[1]='a' string //str == "hallo roc"
   
   
substr str[n:m//截取从索引n到m-1的子串
  • 遍历字符串
    
    
//for遍历,此方式只能遍历存放ASCII//编码的字符串,比如中文就不行for i 0;< len); i++{//... = str[i]}//for-range遍历,此方式可以遍历Unicode//编码的字符串,不担心乱码 index,char range str fmt.Printf("%d %c\n"indexchar)}
  • 计算字符串长度
  
    
//字符串中字符全为ASCII中的字符len)//字符串中含非ASCII的Unicode字符utf8.RuneCountInString)
  • 连接字符串
速度最快的写法:
var buf bytes.Bufferbuf.WriteString"hello ""roc"fmt.Println.String())//hello roc
还有如下两种方式:
strings.Join([]{"hello"" world"},68)">"")
  
     
"hello"+="roc"
原文链接:https://www.f2er.com/go/189923.html

猜你在找的Go相关文章