猿问

如何检查字符串中是否存在特殊字符或者字符是否为 GoLang 中的特殊字符

从输入中读取字符串后,我需要检查其中是否有特殊字符


翻阅古今
浏览 664回答 3
3回答

慕标琳琳

您可以使用 strings.ContainsAny 来查看符文是否存在:package mainimport (&nbsp; "fmt"&nbsp; "strings")func main() {&nbsp; fmt.Println(strings.ContainsAny("Hello World", ",|"))&nbsp; fmt.Println(strings.ContainsAny("Hello, World", ",|"))&nbsp; fmt.Println(strings.ContainsAny("Hello|World", ",|"))}或者如果你想检查是否只有 ASCII 字符,你可以使用 strings.IndexFunc:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; f := func(r rune) bool {&nbsp; &nbsp; &nbsp; &nbsp; return r < 'A' || r > 'z'&nbsp; &nbsp; }&nbsp; &nbsp; if strings.IndexFunc("HelloWorld", f) != -1 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Found special char")&nbsp; &nbsp; }&nbsp; &nbsp; if strings.IndexFunc("Hello World", f) != -1 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Found special char")&nbsp; &nbsp; }}

白衣非少年

根据您对special character的定义,最简单的解决方案可能是for range对您的字符串(产生符文而不是字节)进行循环,并为每个符文检查它是否在您的允许/禁止符文列表中。
随时随地看视频慕课网APP

相关分类

Go
我要回答