Go treats the strings as a series of bytes and it supports both ASCII and Unicode characters, making it suitable to work with text in various languages and character sets.
One of the most common tasks when working with strings is determining the length of a string. In this guide, we will walk you through all the methods and techniques that you can use to get the length of a string in Go.
Method 1: Using the Len() Function
The most common and easiest method of determining the length of a string in Go is using the built-in len() function.
As the name suggests, the function returns the length of the string which denotes to the total number of bytes in the provided string.
Consider the following example:
import (
"fmt"
)
func main() {
str := "https://linuxhint.com"
length := len(str)
fmt.Printf("Len: %d\n", length)
}
Output:
In this example, we declare an “str” string and use the len() function to determine its length. In this case, the string has 21 characters.
Method 2: Using a Loop
A more noob method of determining the length of string is by iterating through the characters until we reach the end of the string.
Although this method provides a little more control to what you can do with each character, it is iterative and inefficient in a large string.
An example is as follows:
import (
"fmt"
)
func main() {
str := "https://linuxhint.com"
length := 0
for range str {
length++
}
fmt.Printf("Len: %d\n", length)
}
In this example, we initialize a length variable to 0 and iterate through each character in the string using a “for range” loop.
We then increment the length variable for each character in the string which gives us the total number of characters in the string.
Method 3: Using Utf8.RuneCountInString()
In some cases, the string whose length you wish to determine might contain multi-byte characters such as Unicode characters.
In such a case, using the len() function returns an incorrect string length value as it counts the bytes and not the characters.
To count the characters correctly, we can use the RuneCountInString() function from the “utf8” package.
An example is as follows:
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "Hello, µ"
length_utf := utf8.RuneCountInString(str)
fmt.Printf("Len(utf8): %d\n", length_utf)
}
In this case, the function counts both the ASCII and Unicode characters to determine the actual number of characters in the string.
Conclusion
In this tutorial, we learned all about the methods and techniques that we can employ to determine the length of a string in Go. We also learned how to use the “utf8” package to accurately count the length of a string if it contains non-ASCII characters.