英文:
Why Go split by newline separator needs to be escaped when received as an argument
问题
包括代码和注释在内的所有内容已经翻译如下:
package main
import (
"fmt"
"os"
"strings"
)
func main() {
arguments := os.Args
words := strings.Split(arguments[1], "\n")
fmt.Println(words)
fmt.Println(words[0])
}
示例:
go run main.go "hello\nthere"
输出:
[hello\nthere]
hello\nthere
预期输出:
[hello there]
hello
为什么换行符的分隔符 "\n"
需要转义为 "\\n"
才能得到预期的结果?
因为如果像这样使用,你不需要转义换行符:https://play.golang.org/p/UlRISkVa8_t
英文:
package main
import (
"fmt"
"os"
"strings"
)
func main() {
arguments := os.Args
words := strings.Split(arguments[1], "\n")
fmt.Println(words)
fmt.Println(words[0])
}
example:
go run main.go "hello\nthere"
output:
[hello\nthere]
hello\nthere
expected:
[hello there]
hello
why does the separator for the newline "\n"
needs to be escaped "\\n"
to get the expected result?
Because you don't need to escape the newline if used like this https://play.golang.org/p/UlRISkVa8_t
答案1
得分: 0
你可以尝试传递一个类似ANSI C的字符串
go run main.go $'hello\nthere'
答案2
得分: 0
你假设Go语言将你的输入视为:
"hello\nthere"
但实际上,Go语言将你的输入视为:
`hello\nthere`
所以,如果你希望该输入被识别为换行符,那么你需要取消引号。但这是一个问题,因为它也没有引号。所以你需要添加引号,然后在继续执行程序之前将其删除:
package main
import (
"fmt"
"strconv"
)
func unquote(s string) (string, error) {
return strconv.Unquote(`"` + s + `"`)
}
func main() {
s, err := unquote(`hello\nthere`)
if err != nil {
panic(err)
}
fmt.Println(s)
}
结果:
hello
there
英文:
You're assuming that Go sees your input as:
"hello\nthere"
but it really sees your input as:
`hello\nthere`
So, if you want that input to be recognized as a newline, then you need to unquote it. But that's a problem, because it doesn't have quotes either. So you need to add quotes, then remove them before you can continue with your program:
package main
import (
"fmt"
"strconv"
)
func unquote(s string) (string, error) {
return strconv.Unquote(`"` + s + `"`)
}
func main() {
s, err := unquote(`hello\nthere`)
if err != nil {
panic(err)
}
fmt.Println(s)
}
Result:
hello
there
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论