dou5454954610 2016-10-30 00:17
浏览 63
已采纳

无法检查字符串。具有用reader.ReadString捕获的字符串的HasSuffix

Overview: I was capturing strings with fmt.Scanln, but one of my needs is that the string must have spaces so I started to use reader.ReadString, I have to check the presence of a suffix in that string to make some replacing, so I used strings.HasSuffix. With strings captured with fmt.Scanln there was no problema but now that I use reader.ReadString it is unabled to find the given suffix in the string.

Is there a clue on what's going on?

Here is a test that isolate the problem, use it in desktop installed Go, not online.

package main

import (
    "bufio"
    "fmt"
    "strings"
    "os"
    "reflect"
)
const TOKEN string = ":="

func validate(expr string) {
    fmt.Println("var type: ", reflect.TypeOf(expr))
    if strings.Contains(expr, TOKEN) {
        fmt.Println(expr, "contains works")
    } else {
        fmt.Println("error with contains")
    }

    if strings.HasSuffix(expr, TOKEN) {
        fmt.Println(expr, "suffix works")
    } else {
        fmt.Println("error with suffix")
    }
}

func main() {
    var expr2 string
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("type something finished with ':='")
    expr1, _ := reader.ReadString('
')
    fmt.Scanln(&expr2)

    fmt.Println("validation with reader: ")
    validate(expr1)
    fmt.Println()
    fmt.Println("validation with Scanln: ")
    validate(expr2)
}
  • 写回答

1条回答 默认 最新

  • dro60731 2016-10-30 00:47
    关注

    As @Tim mentioned the output of reader.ReadString(' ') includes ' ' as the last character and fmt.Scanln does not do that. You can either do const TOKEN string = ":= " or remove the ' ' from the end of the string.

    Update :

    There are cases where occurs as a suffix instead of the usually expected (Windows Machines ?)

    fmt.Scanln handles that case as well, as per fmt godoc.

    In all the scanning functions, a carriage return followed immediately by a newline is treated as a plain newline ( means the same as ).

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭