Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator
string length
len()

How to find the length of a string in Golang

Gutha Vamsi Krishna

Overview

In Golang, we use the following two methods to find the length of a string:

  • len()
  • RuneCountInString()

len() method

The len() method returns the number of bytes in a string.

Syntax

len(str)

Parameters

This method takes a string str as a parameter.

Return value

This method returns the length of the string.

Example

package main

import(
    "fmt"
)

//Program starts from here
func main() {
    //provide the string here
    var str = "educative"

    //calculate length
    var length = len(str)

    //display length
    fmt.Println("Length of the string is :", length)
}
Length of a string using len() method

Explanation

  • Line 8: We call the main() function.
  • Line 10: We declare the string str.
  • Line 13: We pass the string str as a parameter to the len() method. Next, we assign length to the length variable, which is returned by len().
  • Line 16: We use the println() function to print the length.

RuneCountInString() method

The RuneCountInString() method is provided by the utf8 package.

Syntax

RuneCountInString(str)

Parameters

This function accepts a string as its parameter.

Return value

It returns the length of the string.

Example

package main

//import utf8 package
import (
    "unicode/utf8"
    "fmt"
)

//Program exection starts here
func main() {
    //provide the string here
    var str = "educative"

    //calculate length
    var length = utf8.RuneCountInString(str)

    //display length
    fmt.Println("Length of the string is :", length)
}
Length of a string using RuneCountInString method

Explanation

Most of the explanation is same as for the len() method.

  • Line 5: We import the utf8 package.
  • Line 15: We pass the string str as a parameter to RuneCountInString(). We assign the output length to the length variable.

When to use which method

We have learned two ways to find the length of a string in Golang.

For normal characters, we can use any of the methods. However, if there are any special characters like the Black Chess Queen ♛, the len() method returns a length value output which is not accepted. In such cases, we opt for RuneCountInString().

RELATED TAGS

golang
communitycreator
string length
len()
RELATED COURSES

View all Courses

Keep Exploring