博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
golang中获取字符串长度与遍历的方法
阅读量:3987 次
发布时间:2019-05-24

本文共 880 字,大约阅读时间需要 2 分钟。

package mainimport (	"bytes"	"fmt"	"strings"	"unicode/utf8")func main() {
str := "wo中国\n" // Count counts the number of non-overlapping instances of substr in s. // If substr is an empty string, Count returns 1 + the number of Unicode code points in s. d1 := strings.Count(str, "") - 1 // strings.Count 和 bytes.Count,这两个函数的用法是相同,只是一个作用在字符串上,一个作用在字节上 d2 := bytes.Count([]byte(str), nil) - 1 // 将每个字符使用4个字节来存储 d3 := len([]rune(str)) // RuneCountInString is like RuneCount but its input is a string. d4 := utf8.RuneCountInString(str) d5 := utf8.RuneCount([]byte(str)) fmt.Println(d1) fmt.Println(d2) fmt.Println(d3) fmt.Println(d4) fmt.Println(d5)}

遍历字符串

func main() {
str := "I love 中国" for _, v := range str {
fmt.Print(string(v)) // I love 中国 } fmt.Println() for i := 0; i < len(str); i++ {
fmt.Print(string(str[i])) // I love 中å }}

for...range 支持 unicode 字符集。

转载地址:http://acaui.baihongyu.com/

你可能感兴趣的文章
javap与 i++,++i
查看>>
自定义类加载器
查看>>
SimpleDateFormat 的线程安全问题
查看>>
Joda-Time 简介
查看>>
Comparable与Comparator
查看>>
一个死锁的例子
查看>>
IO流(一)
查看>>
设计模式-装饰器模式
查看>>
ping github 请求超时
查看>>
Try Redis(Redis 简介)
查看>>
设计模式-代理模式
查看>>
[书]java并发编程的艺术笔记
查看>>
设计模式-模板模式
查看>>
TCP协议的3次握手与4次挥手
查看>>
JDK6和JDK7中的substring()方法
查看>>
mysql字符集
查看>>
Missing artifact org.apache.qpid:proton-jms:jar:0.3.0-fuse-2
查看>>
mysql索引及sql优化
查看>>
eclipse创建maven war项目不能自动生成web.xml
查看>>
在虚拟机中安装Centos6.5
查看>>