英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论