How to find the length of a string in Golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I’m going to show how do you check the length of a string in Golang, in golang to find string length we have to first convert the string to a char array then we can easily get the length of an array using len() method.

The len() method expects an array, it will count an array of elements and return the number of elements.

Let’s start today’s tutorial How to find the length of a string in Golang?

Here, we are going to do

  1. Create a string variable
  2. Convert string to an array of char
  3. Use len() method to get length
package main
func main() {
    // create string variable
    var str = "ab£"

    // convert string to array of char
    // Use `len()` method to get length
    var length = len([]rune(str))
    println("Length of the string is : ", length)
    println("Output of len(str) is : ", len(str))

When you run the above program it will print the length of the array and the length of the string.

find,length of a string, golang

Try it yourself

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 getting an invalid count of string.

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us


Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts