英文:
Go: What's the best way to detect invalid JSON string characters?
问题
检测一个Go字符串中是否包含在JSON字符串中无效的字符,最好且最高效的方法是什么?换句话说,与这个Java问题的答案相比,Go语言中的等效方法是什么?是否只需使用strings.ContainsAny(假设ASCII控制字符)?
ctlChars := string([]byte{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127,
})
if strings.ContainsAny(str, ctlChars) {
println("包含控制字符")
}
英文:
What's the best, most efficient way to detect whether a Go string contains characters that are invalid in JSON strings? In other words, what's the Go equivalent to this answer to this Java question? Is it just to use
strings.ContainsAny (assuming the ASCII control characters)?
ctlChars := string([]byte{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127,
})
if strings.ContainsAny(str, ctlChars) {
println("has control chars")
}
答案1
得分: 2
如果你想识别控制字符(就像你指向的Java问题的答案中所提到的),你可以使用unicode.IsControl
来获得一个更简单的解决方案。
https://golang.org/pkg/unicode/#IsControl
func containsControlChar(s string) bool {
for _, c := range s {
if unicode.IsControl(c) {
return true
}
}
return false
}
Playground: https://play.golang.org/p/Pr_9mmt-th
英文:
If you are looking to identify control characters (as in the answers to the Java question you pointed to), you might want to use unicode.IsControl
for a simpler solution.
https://golang.org/pkg/unicode/#IsControl
func containsControlChar(s string) bool {
for _, c := range s {
if unicode.IsControl(c) {
return true
}
}
return false
}
Playground: https://play.golang.org/p/Pr_9mmt-th
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论