Go – String Length

To get the length of a String in Go programming, convert the string to array of runes, and pass this array to len() function.

A string contains characters as unicode points, not bytes. len(string) returns the number of bytes in this string, but not the number of characters. Therefore, we are converting the string to rune array and then finding the array length.

Syntax

The syntax to find the length of string str is

</>
Copy
 len([]rune(str))

The expression returns an integer representing the number of characters in the string str.

Examples

In the following program, we will define a string x and find its length using len() function.

example.go

</>
Copy
package main

func main() {
	var str = "Hello World"
	var length = len([]rune(str))
	println("Length of the string is :", length)
}

Output

Length of the string is : 11

Now, let us take a string with some characters whose length is more than a byte, and find out the length of string.

example.go

</>
Copy
package main

func main() {
	var str = "ab£"
	var length = len([]rune(str))
	println("Length of the string is : ", length)
	println("Output of len(str) is : ", len(str))
}

Output

Length of the string is :  3
Output of len(str) is :  4

Please observe the difference between len(string) and len([]rune(string)).

Conclusion

In this Golang Tutorial, we learned how to find the length of a string using runes and len() function.