【问题标题】:cmd line parameter string.Contains behaving differently from hardcoded parametercmd 行参数字符串。包含与硬编码参数不同的行为
【发布时间】:2016-11-21 12:09:43
【问题描述】:

我希望澄清一下为什么这两个 strings.Contains() 调用的行为不同。

package main

import (
    "strings"
    "os"
    "errors"
    "fmt"
)

func main() {

    hardcoded := "col1,col2,col3\nval1,val2,val3"
    if strings.Contains(hardcoded, "\n") == false {
        panic(errors.New("The hardcoded string should contain a new line"))
    }
    fmt.Println("New line found in hardcoded string")

    if len(os.Args) == 2 {
        fmt.Println("parameter:", os.Args[1])
        if strings.Contains(os.Args[1], "\n") == false {
            panic(errors.New("The parameter string should contain a new line."))
        }
        fmt.Println("New line found in parameter string")
    }

}

如果我用

运行它
go run input-tester.go col1,col2,col3\\nval1,val2,val3

我得到以下内容

New line found in hardcoded string
parameter: col1,col2,col3\nval1,val2,val3
panic: The parameter string should contain a new line.

goroutine 1 [running]:
panic(0x497100, 0xc42000e310)
    /usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
    /home/user/Desktop/input-tester.go:21 +0x343
exit status 2

我可以看到打印出来的字符串与硬编码的字符串格式相同,但 string.Contains() 没有找到“\n”。

我猜这是我的疏忽。谁能解释我遗漏或误解的内容?

【问题讨论】:

  • 如果我们使用 ` \n ` 作为命令行参数,它就可以工作
  • 哦,亲爱的 - 似乎之前的一位受访者删除了他们的评论,然后对这个问题投了反对票,然后访问了我的个人资料并反对我以前的所有问题:D 可怜的约翰

标签: go


【解决方案1】:

它的行为不同,因为在硬编码中 \n 被视为新行参数。 在命令行参数中,参数类型是字符串,其中给定条件是“\n”,它被视为新行参数。 只需 ` \n 与两个连续的字符“\”和“n”比较,而不是与“\n”一个换行符。

所以对于命令行参数使用,

if strings.Contains(os.Args[1], `\n`) == false {
        panic(errors.New("The parameter string should contain a new line."))
    }

参考:https://golang.org/ref/spec#String_literals

原始字符串文字是反引号之间的字符序列,如foo。在引号内,可以出现除反引号外的任何字符。原始字符串文字的值是由引号之间的未解释(隐式 UTF-8 编码)字符组成的字符串;特别是,反斜杠没有特殊含义,字符串可能包含换行符。

【讨论】:

  • 很好的答案。谢谢你。
猜你喜欢
  • 2015-02-24
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多