zoukankan      html  css  js  c++  java
  • golang中获取字符串长度的几种方法

    一、获取字符串长度的几种方法

    1.  
      - 使用 bytes.Count() 统计
    2.  
      - 使用 strings.Count() 统计
    3.  
      - 将字符串转换为 []rune 后调用 len 函数进行统计
    4.  
      - 使用 utf8.RuneCountInString() 统计

    例:

    1.  
      str:="HelloWord"
    2.  
      l1:=len([]rune(str))
    3.  
      l2:=bytes.Count([]byte(str),nil)-1)
    4.  
      l3:=strings.Count(str,"")-1
    5.  
      l4:=utf8.RuneCountInString(str)
    6.  
      fmt.Println(l1)
    7.  
      fmt.Println(l2)
    8.  
      fmt.Println(l3)
    9.  
      fmt.Println(l4)
    10.  
      打印结果:都是 9
    
    

    二、strings.Count函数和bytes.Count函数

    这两个函数的用法是相同,只是一个作用在字符串上,一个作用在字节上


    strings中的Count方法

    func Count(s, sep string) int{}

       判断字符sep在字符串s中出现的次数,没有找到则返回-1,如果为空字符串("")则返回字符串的长度+1

    例:

    1.  
      str:="HelloWorld"
    2.  
      fmt.Println(strings.Count(str,"o"))  //打印 o 出现的次数,打印结果为2

    注:在 Golang 中,如果字符串中出现中文字符不能直接调用 len 函数来统计字符串字符长度,这是因为在 Go 中,字符串是以 UTF-8 为格式进行存储的,在字符串上调用 len 函数,取得的是字符串包含的 byte 的个数。

    1.  
      str:="HelloWorld"
    2.  
       
    3.  
      str1 := "Hello, 世界"
    4.  
      fmt.Println(len(str1)) // 打印结果:13
    5.  
      fmt.Println(len(str)) //打印结果:9 (如果是纯英文字符的字符串,可以使用来判断字符串的长度)
    6.  

  • 相关阅读:
    从函数作用域和块级作用域看javascript的作用域链
    基于vue实现一个简单的MVVM框架(源码分析)
    发布-订阅模式
    希尔排序
    直接插入排序
    选择排序
    React Fiber源码分析 第三篇(异步状态)
    React Fiber源码分析 第二篇(同步模式)
    React Fiber源码分析 第一篇
    数据结构 之 树总结
  • 原文地址:https://www.cnblogs.com/405845829qq/p/9472955.html
Copyright © 2011-2022 走看看