doulu1945 2018-08-23 22:41
浏览 10
已采纳

字符串格式截断值

This is going to be a simple question to answer, I am sure of it. I am brand new to Go and I can't figure out what is happening.

package main

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

func main() {
    fmt.Print("*A basic GoLang/Native example*

")
    fmt.Print("Enter your name:
")

    reader := bufio.NewReader(os.Stdin)
    name, _ := reader.ReadString('
')
    name = strings.TrimSuffix(name, "
")

    fmt.Printf("Hello, %s, how are you?", name)

    reader.ReadString('
')

}

I am removing the newline which is stored in variable name from reading in the user input, but the last Printf statement is truncating Hello, from the line.

  • 写回答

1条回答 默认 最新

  • dtnd30892 2018-08-23 23:05
    关注

    I think you are looking for strings.TrimSpace.

    To remove the leading and trailing white spaces use this.

    Change this line from

    name = strings.TrimSuffix(name, " ")

    to

    name = strings.TrimSpace(name)

    Output:

    *A basic GoLang/Native example*
    
    Enter your name:
    Source Cast
    Hello, Source Cast, how are you?
    

    It is working fine for both Windows and Linux.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录