Different ways ways to check Length of a String output in Golang

In this blog post, You will learn three programs.

  • The first program is the Length or count of characters/bytes of a String
  • The second program is Length of runes in a String
  • Third Program is to find the length of string using a pointer

String is a sequence of characters that contains one or more words. In Golang, String is read-only of arbitrary bytes. Its length is the number of characters in a string.

For example, the Given input string is “Cloudhadoop”, and the length of the string is 11.

How to find Length or count of Character/bytes of a String in Golang

In this program, the Inbuilt `len() function is used to calculate the length of the character of a string.

Here is a syntax of len function🔗

func len(input Type) int

This function accepts input parameters of type like an array, slice, strings, channel.

package main
import (
    "fmt"
)

func main() {
    str1: = "This is test program"
    fmt.Println(len(str1)) //11
}

Output:

20

How to find Length of runes in a String in Golang Example program

Package unicode/utf8 provides RuneCountInString function to find out runes count of a string.

Here is a RuneCountInString function Syntax

func RuneCountInString(s string) (n int)

Here is a program to check the runes count of a string using the RuneCountInString function.

package main

import (
 "fmt"
 "unicode/utf8"
)

func main() {
 str := "Cloudhadoop"
 fmt.Println(utf8.RuneCountInString(str)) // 11

}

output:

11

How to calculate lengths of a string using pointer in Golang

Address of variable finds using ampersand(&) symbol.

length of String using pointer or address can be found using \*(star) followed by variable.

Here is an example checking string pointer length

package main

import (
    "fmt"
)

func main() {
    str: = "cloudhadoop"
    address: = & str
    fmt.Println(len( * address))

}

Output:

11