How to check if there is a special character in string or if a character is a special character in GoLang

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

How to check if there is a special character in string or if a character is a special character in GoLang

问题

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

英文:

After reading a string from the input, I need to check if there is a special character in it

答案1

得分: 17

你可以使用strings.ContainsAny函数来判断是否存在一个rune字符:

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ContainsAny("Hello World", ",|"))
	fmt.Println(strings.ContainsAny("Hello, World", ",|"))
	fmt.Println(strings.ContainsAny("Hello|World", ",|"))
}

或者,如果你想检查是否只有ASCII字符,你可以使用strings.IndexFunc函数:

package main

import (
	"fmt"
	"strings"
)

func main() {
	f := func(r rune) bool {
		return r < 'A' || r > 'z'
	}
	if strings.IndexFunc("HelloWorld", f) != -1 {
		fmt.Println("找到特殊字符")
	}
	if strings.IndexFunc("Hello World", f) != -1 {
		fmt.Println("找到特殊字符")
	}
}
英文:

You can use strings.ContainsAny to see if a rune exists:

package main

import (
  &quot;fmt&quot;
  &quot;strings&quot;
)

func main() {
  fmt.Println(strings.ContainsAny(&quot;Hello World&quot;, &quot;,|&quot;))
  fmt.Println(strings.ContainsAny(&quot;Hello, World&quot;, &quot;,|&quot;))
  fmt.Println(strings.ContainsAny(&quot;Hello|World&quot;, &quot;,|&quot;))
}

Or if you want to check if there are only ASCII characters, you can use strings.IndexFunc:

package main

import (
	&quot;fmt&quot;
	&quot;strings&quot;
)

func main() {
	f := func(r rune) bool {
		return r &lt; &#39;A&#39; || r &gt; &#39;z&#39;
	}
	if strings.IndexFunc(&quot;HelloWorld&quot;, f) != -1 {
		fmt.Println(&quot;Found special char&quot;)
	}
	if strings.IndexFunc(&quot;Hello World&quot;, f) != -1 {
		fmt.Println(&quot;Found special char&quot;)
	}
}

答案2

得分: 3

根据你对“特殊字符”的定义,最简单的解决方案可能是在字符串上进行for range循环(产生的是符文而不是字节),并且对于每个符文,检查它是否在你的允许/禁止符文列表中。

有关字符串、字节和符文之间的关系,请参阅Go中的字符串、字节、符文和字符

Playground示例

package main

var allowed = []rune{'a','b','c','d','e','f','g'}

func haveSpecial(input string) bool {
	for _, char := range input {
		found := false
		for _, c := range allowed {
			if c == char {
				found = true
				break
			}
		}
		if !found {
			return true
		}
	}
	return false
}

func main() {
	cases := []string{
		"abcdef",
		"abc$€f",
	}
	for _, input := range cases {
		if haveSpecial(input) {
			println(input + ": NOK")
		} else {
			println(input + ": OK")
		}
	}
}
英文:

Depending on your definition of special character, the simplest solution would probably to do a for range loop on your string (which yield runes instead of bytes), and for each rune check if it is in your list of allowed/forbidden runes.

See Strings, bytes, runes and characters in Go for more about the relations between string, bytes and runes.

Playground example

package main

var allowed = []rune{&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;}

func haveSpecial(input string) bool {
	for _, char := range input {
		found := false
		for _, c := range allowed {
			if c == char {
				found = true
				break
			}
		}
		if !found {
			return true
		}
	}
	return false
}

func main() {
	cases := []string{
		&quot;abcdef&quot;,
		&quot;abc$€f&quot;,
	}
	for _, input := range cases {
		if haveSpecial(input) {
			println(input + &quot;: NOK&quot;)
		} else {
			println(input + &quot;: OK&quot;)
		}
	}
}

答案3

得分: -1

你想使用unicode包,它有一个很好的函数可以检查符号。

https://golang.org/pkg/unicode/#IsSymbol

package main

import (
	"fmt"
	"unicode"
)

func hasSymbol(str string) bool {
	for _, letter := range str {
		if unicode.IsSymbol(letter) {
			return true
		}
	}
	return false
}

func main() {	
	var strs = []string {
		"A quick brown fox",
		"A+quick_brown&lt;fox",
	}
	
	for _, str := range strs {
		if hasSymbol(str) { 
			fmt.Printf("字符串 '%v' 包含符号。\n", str)
		} else {
			fmt.Printf("字符串 '%v' 不包含符号。\n", str)	
		}
	}
}

这将提供以下输出:

字符串 'A quick brown fox' 不包含符号。
字符串 'A+quick_brown&lt;fox' 包含符号。
英文:

You want to use the unicode package, which has a nice function to check for symbols.

https://golang.org/pkg/unicode/#IsSymbol

package main

import (
	&quot;fmt&quot;
	&quot;unicode&quot;
)

func hasSymbol(str string) bool {
	for _, letter := range str {
		if unicode.IsSymbol(letter) {
			return true
		}
	}
	return false
}

func main() {	
	var strs = []string {
		&quot;A quick brown fox&quot;,
		&quot;A+quick_brown&lt;fox&quot;,
	}
	
	for _, str := range strs {
		if hasSymbol(str) { 
			fmt.Printf(&quot;String &#39;%v&#39; contains symbols.\n&quot;, str)
		} else {
			fmt.Printf(&quot;String &#39;%v&#39; did not contain symbols.\n&quot;, str)	
		}
	}
}

This will provide the following output:

String &#39;A quick brown fox&#39; did not contain symbols.
String &#39;A+quick_brown&lt;fox&#39; contains symbols.

答案4

得分: -2

我最终做了这样的事情:

alphabet := "abcdefghijklmnopqrstuvwxyz"
alphabetSplit := strings.Split(alphabet, "")
inputLetters := strings.Split(input, "")

for index, value := range inputLetters {
        special := 1
        for _, char := range alphabetSplit {
            if char == value {
                special = 0
                break
            }
        }
英文:

I ended up doing something like this

alphabet := &quot;abcdefghijklmnopqrstuvwxyz&quot;
alphabetSplit := strings.Split(alphabet, &quot;&quot;)
inputLetters := strings.Split(input, &quot;&quot;)

for index, value := range inputLetters {
        special:=1
        for _, char :=range alphabetSplit{
            if char == value {
                special = 0
                break
            }
        }

It might have anything wrong because since I used it to something specific i had to edit to post it here

huangapple
  • 本文由 发表于 2015年8月12日 17:57:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/31961882.html
匿名

发表评论

匿名网友

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

确定