Method in golang to get the number of strings

  • 2020-07-21 08:27:11
  • OfStack

In golang, the len function cannot be directly used to count the length of the string. After looking at the source code, it is found that the string is stored in the format of UTF-8, indicating that the len function is to obtain the number containing byte


// string is the set of all strings of 8-bit bytes, conventionally but not
// necessarily representing UTF-8-encoded text. A string may be empty, but
// not nil. Values of string type are immutable.

For example, "Hello, world"


s := "Hello,  The world "
fmt.Println(len(s)) // 13
fmt.Println([]byte(s)) // [72 101 108 108 111 44 32 228 184 150 231 149 140]

Since it is stored in byte, it is natural to take the length of byte


- bytes.Count() 
- strings.Count() 
-  Converts a string to  []runee  After the call  len  function 
-  use  utf8.RuneCountInString() 

package main
import (
  "bytes"
  "fmt"
  "strings"
  "testing"
  "unicode/utf8"
)
/*
 in  golang  Can not be used directly in  len  Function to count the length of the string, looked under the source found string is  UTF-8  Stored in a format, the specification  len  The function is to get inclusion  byte  The number of 
*/
func main() {
  s := "hello,  The world "
  fmt.Println(len(s))  // 13
  fmt.Println([]byte(s)) // [72 101 108 108 111 44 32 228 184 150 231 149 140]
  fmt.Print(f1(s))
}
func f1(s string) int {
  return bytes.Count([]byte(s), nil) - 1
}
func f2(s string) int {
  return strings.Count(s, "") - 1
}
func f3(s string) int {
  return len([]rune(s))
}
func f4(s string) int {
  return utf8.RuneCountInString(s)
}
var s = "Hello,  The world "
func Benchmark1(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f1(s)
  }
}
func Benchmark2(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f2(s)
  }
}
func Benchmark3(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f3(s)
  }
}
func Benchmark4(b *testing.B) {
  for i := 0; i < b.N; i++ {
    f4(s)
  }
}

In the golang ldea configuration I did not see the benchamark configuration, always saying the package is wrong, enter it on the command line

go test stringCount_test.go -bench ".*"

The following results are obtained

[

Benchmark1-12 100000000 17.7 ns/op
Benchmark2-12 100000000 14.0 ns/op
Benchmark3-12 100000000 14.5 ns/op
Benchmark4-12 100000000 13.1 ns/op

]

The fastest is utf8.RuneCountInString()

conclusion

The above is the method of getting the number of strings in golang introduced by this site. I hope it will be helpful if you have any

Please leave me a message if you have any questions. This site will reply to you in time. Thank you very much for your support!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!


Related articles: