doudou3213 2016-11-21 12:09
浏览 25
已采纳

命令行参数字符串。其行为与硬编码参数不同

I'm looking to get some clarification on why these two strings.Contains() calls behave differently.

package main

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

func main() {

    hardcoded := "col1,col2,col3
val1,val2,val3"
    if strings.Contains(hardcoded, "
") == 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], "
") == false {
            panic(errors.New("The parameter string should contain a new line."))
        }
        fmt.Println("New line found in parameter string")
    }

}

If I run this with

go run input-tester.go col1,col2,col3\
val1,val2,val3

I get the following

New line found in hardcoded string
parameter: col1,col2,col3
val1,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

I can see that the string printed out is the same format as the string that is hardcoded yet the string.Contains() doesn't find the " ".

I'm guessing this is an oversight on my part. Can anyone explain what I'm missing or misunderstanding?

  • 写回答

1条回答 默认 最新

  • drwkqwa82140 2016-11-21 13:19
    关注

    It behaves differently because in hardcoded is considered as new line parameter. And in command line arguments , argument type is string, where given condition is for " " which is considered as new line parameter. Simply ` compaires with two consecutive characters "\" and "n" not with " " a new line character.

    So for command line arguments use,

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

    Reference : https://golang.org/ref/spec#String_literals

    Raw string literals are character sequences between back quotes, as in foo. Within the quotes, any character may appear except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看