A string contains sequence of characters as unicode points unless bytes. The len() returns the number of bytes allocated to the string instead number of characters. Hence, It needs to convert into rune type array to find length of string.
string_variable : A string variable to check the length
1 package main
2
3 import "fmt"
4
5 func main() {
6 var str = "Hello world !£"
7
8
9 fmt.Println("Str1 bytes len() : ", len(str))
10
11
12 fmt.Println("Str1 chars len() : ", len([]rune(str)))
13 }
In the above example, we have define string variable with pound symbol. A symbol takes two bytes to store character. A rune data type allows to store long range ASCII value to store symbols. If a string contain special character need to convert into rune type and then find the length of string.
1 Str1 bytes len() : 15
2 Str1 chars len() : 14
Custom function to determine length
Custom function to determine length
1 package main
2
3 import "fmt"
4
5 func main() {
6 var str = "Hello world !£"
7
8 i := 0
9 for range str {
10 i++
11 }
12
13 fmt.Println("A length of string is :", i)
14 }
In the above example, a string declared and initialized with string literal that includes 14 characters and one special symbol. A string characters are iterated using for range loop which increments variable i in each iteration. Once a each characters iterated, variable i value will be represents a length of character that will be printed. It does not include special character in the length.
1 A length of string is : 14
Determine length using RuneCountInString()
determine length using RuneCountInString()
1 package main
2
3 import (
4 "fmt"
5 "unicode/utf8"
6 )
7
8 func main() {
9 var str = "Hello world !£"
10
11
12 length := utf8.RuneCountInString(str)
13 fmt.Println("A length of string is :", length)
14 }
In the above example, a string declare and intialized with characters that includes special character. A module unicode/utf8 is imported and a RuneCountInString() function is called which will return length of character by excluding special character. A function RuneCountInString() returns number of characters present in the string. A result assigned to the variable that will be printed.
1 A length of string is : 14
Determine length of string using bytes module
Determine length of string using bytes module
1 package main
2
3 import (
4 "fmt"
5 "bytes"
6 )
7
8 func main() {
9 var str = "Hello world !£"
10
11
12 length := bytes.Count([]byte(str), nil)
13 fmt.Println("A length of string is :", length)
14 }
In the above example, a string variable declared and initialized with string literal that includes special character. A bytes module Count() function is called that returns number of bytes occupied by the string. A number is assigned to the variable that will be printed. Hence, it includes special symbol in the length count.
1 A length of string is : 15
Related options for your search