Go Program to Find String Length

Write a Go program to find the length of a string. In this Golang example, we used the built-in len function to find the given string length.

package main

import (
    "fmt"
)

func main() {

    str := "Tutorial Gateway"
    fmt.Println(str)

    length := len(str)
    fmt.Println("The Length of a Given String = ", length)
}
Go Program to Find String Length 1

Go Program to Find String Length using for loop

In this example, for loop (for _, l := range str) iterates all the string characters. Within the loop, we increment the length value (length++) from 0 and then printing the final string length.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter Any String to find Length = ")
    str, _ := reader.ReadString('\n')
    length := 0
    for _, l := range str {
        fmt.Printf("%c  ", l)
        length++
    }
    fmt.Println("\nThe Length of a Given String = ", length-1)
}
Enter Any String to find Length = hello world
h  e  l  l  o     w  o  r  l  d  
  
The Length of a Given String =  11

The Golang unicode/utf8 package has a RuneCountInString function that counts the total runes or characters in a string. So, we used this function to find the string length.

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {

    str := "Golang Programs"
    fmt.Println(str)

    length := utf8.RuneCountInString(str)
    fmt.Println("The Length of a Given String = ", length)
}
Golang Programs
The Length of a Given String =  15