如何在Go中打印os.Args[1:]而不带括号?

huangapple go评论81阅读模式
英文:

How to print os.args[1:] without braces in Go?

问题

当我尝试使用以下代码打印命令行参数时:

fmt.Println(os.Args[1:])

我得到的结果是:

[Gates Bill]

如何去掉参数周围的 []?而且 Go 似乎吞掉了参数中的所有逗号,我该如何得到以下输出:

姓, 名
Gates, Bill
英文:

When I tried to print command line arguments using

	fmt.Println(os.Args[1:])

I got result like

[Gates Bill]

How can I get rid of the [] around the arguments? And Go seems to eat all the commas in the arguments, how can I get the output like

Last name, First name
Gates, Bill

答案1

得分: 10

你应该使用strings.Join来实现。尝试使用以下代码:

fmt.Printf("%s, The Art of Computer Programming的作者", strings.Join(os.Args[1:], ", "))

Join函数会在每个参数之间插入, ,并返回一个字符串。

英文:

You should use strings.Join for this. Try,

fmt.Printf("%s, Author of The Art of Computer Programming", strings.Join(os.Args[1:], ", "))

Join returns a string with ", " inserted between each argument.

答案2

得分: 1

原因是你将一个切片传递给了print命令,所以它输出了括号。

你需要做的是将每个命令放入一个字符串中,根据需要进行打印。

firstname := os.Args[1]
lastname := os.Args[2]
fmt.Println(lastname + ", " + firstname)

你还应该查看strings包,正如Chandru指出的那样。里面有很多有用的函数来处理字符串。

参考链接:https://golang.org/pkg/strings/

英文:

The reason it's outputting the brackets is because you're passing a slice into the print command.

What you want to do is take each command and put them into a string to be printed as needed.

firstname := os.Args[1]
lastname := os.Args[2]
fmt.Println(lastname + ", " + firstname)

You should also take a look at the strings package as was pointed out by Chandru. There's a bunch of goodies in there to help with dealing with strings.

See: https://golang.org/pkg/strings/

huangapple
  • 本文由 发表于 2016年1月11日 16:08:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/34716700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定