find the length of a string in go

In Go, the length of a string can be calculated using the built-in len() function.

Here's an example:

main.go
package main

import "fmt"

func main() {
    str := "Hello, World!"
    length := len(str)
    fmt.Printf("Length of the string is %d", length) // Output: Length of the string is 13
}
185 chars
10 lines

Note that in Go, strings are encoded in UTF-8 encoding, so the len() function returns the number of bytes in the string, not the number of characters. To get the number of characters, you can use the utf8.RuneCountInString() function:

main.go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    str := "Hello, 世界!"
    length := utf8.RuneCountInString(str)
    fmt.Printf("Length of the string is %d", length) // Output: Length of the string is 9
}
227 chars
13 lines

This will correctly give the length of the string as 9, which is the number of Unicode code points in the string (including the Chinese characters).

related categories

gistlibby LogSnag