从用户输入中获取字符串长度

我想获取字符串长度,这是我的代码:

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Text to send: ")
    text,_ := reader.ReadString('\n')
    fmt.Print(strconv.Itoa(len(text)))

}

对于输入:aaa

输出为5,但应为3

我知道我可以从结果中减去-2,但是我想要“更清洁”的方式

h12405asdf 回答:从用户输入中获取字符串长度

您需要从输入中删除空格:

import (
    "fmt"
    "strings"
)

func main() {
     reader := bufio.NewReader(os.Stdin)
     fmt.Print("Text to send: ")
     text,_ := reader.ReadString('\n')
     newText := strings.TrimSpace(text)
     fmt.Print(strconv.Itoa(len(newText)))    
}
本文链接:https://www.f2er.com/3128127.html

大家都在问