{"id":2317,"date":"2020-06-20T21:01:04","date_gmt":"2020-06-20T15:31:04","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=2317"},"modified":"2021-04-06T18:10:40","modified_gmt":"2021-04-06T12:40:40","slug":"length-of-string-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/length-of-string-golang\/","title":{"rendered":"Length of string in Go (Golang)"},"content":{"rendered":"\n
In Golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other characters are between 1 -4 bytes. To understand it more consider the below string<\/p>\n\n\n\n
sample := \"a\u00a3c\"<\/code><\/pre>\n\n\n\nIn above string<\/p>\n\n\n\n
- ‘a’ takes one byte as per UTF-8<\/li>
- ‘\u00a3’ takes two bytes as per UTF-8<\/li>
- ‘b’ takes one byte as per UTF-8<\/li><\/ul>\n\n\n\n
The above string has 1+2+1 = 4 bytes altogether. Therefore when we try to print the length of the string using the standard len()<\/strong> function it will output 4 and not 3 as len()<\/strong> function returns the number of bytes in the string.<\/p>\n\n\n\nfmt.Printf(\"Length is %d\\n\", len(sample))<\/code><\/pre>\n\n\n\nHence standalone for loop cannot be used to iterate over all characters of a string as it will iterate over bytes and not character. So below for<\/strong> loop will instead iterate four times and the print value corresponding to a byte at that index.<\/p>\n\n\n\nfor i := 0; i < len(sample); i++ {\n fmt.Printf(\"%c\\n\", sample[i])\n }<\/code><\/pre>\n\n\n\nIt will output below string which is not same as sample <\/strong>string<\/p>\n\n\n\na\u00c2\u00a3b<\/code><\/pre>\n\n\n\nNot we have mentioned the above limitation of using len() function and for loop, let's see two ways of calculating the length of the string.<\/p>\n\n\n\n
- Using the RuneCountInString<\/strong> method of the utf8 package<\/li>
- Using for-range loop<\/li>
- By converting string to a rune array.<\/li><\/ul>\n\n\n\n