Go 程序查找字符串长度

编写一个 Go 程序来查找字符串的长度。在此示例中,我们使用内置的 len 函数来查找给定字符串的长度。

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

使用 for 循环查找字符串长度的 Go 程序

在此示例中,for 循环(for _, l := range str)会遍历所有字符串字符。在循环中,我们将长度值(length++)从 0 开始递增,然后打印最终的字符串长度。

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

Golang 的 unicode/utf8 包有一个 RuneCountInString 函数,可以计算字符串中的总 runes 或字符。因此,我们使用此函数来查找字符串长度。

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