Several methods of getting string length in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

A few ways to get the length of a string

-Use bytes. COUNT () statistics-use strings. COUNT () Statistics-Converts a string to []rune] and calls the Len function for statistics-using UTF8. Runecountinstring () Statistics

Example :

str:= "Helloword" L1:=len ([]rune (str)) l2:=bytes. Count ([]byte (str), nil)-1) l3:=strings. Count (str, "") -1l4:=utf8. Runecountinstring (str) FMT. Println (L1)
Fmt. PRINTLN (L2)
Fmt. Println (L3)
Fmt. Println (L4)
Print Results: all 9

Second, strings. The Count function and the Bytes.count function

The usage of these two functions is the same, just a function on the string, one acting on the byte


The Count method in strings

Func Count (S, Sep string) int{}
Determines the number of occurrences of the character Sep in the string s, returns 1 if it is not found, and returns the length of the string if it is an empty string ("") +1

Cases:

str:= "HelloWorld" FMT. PRINTLN (Strings. Count (str, "O"))  //print o number of occurrences, printing result is 2

Note: In Golang, if Chinese characters appear in the string, the Len function cannot be called directly to count the string character length, because in Go, the string is stored in UTF-8 format, and the Len function is called on the string to get the number of bytes contained in the string.

str:= "HelloWorld"

STR1: = "Hello, World" FMT. Println (Len (STR1))//print Result: 13
Fmt. PRINTLN (len (str))  //Print Result: 9  (if it is a string of plain English characters, you can use it to determine the length of the string)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.