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

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,但是我想要“更清洁”的方式

最佳答案

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

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)))
}

关于go - 从用户输入获取字符串长度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58791515/

10-11 20:20
查看更多