确定一个字符是字母还是数字。

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

Determine whether a character is a letter or number

问题

鉴于Go字符串是Unicode的,是否有一种安全的方法来确定一个字符(比如字符串中的第一个字母)是字母还是数字?过去,我通常会根据ASCII字符范围进行检查,但我怀疑在Unicode字符串中这种方法可能不太可靠。

英文:

Given that Go strings are unicode, is there a way to safely determine whether a character (such as the first letter in a string) is a letter or a number? In the past I would just check against ASCII character ranges, but I doubt that would be very reliable with unicode strings.

答案1

得分: 5

你可以在unicode包中始终使用func IsNumber(r rune) bool

if unicode.IsNumber(rune) { ... }

请注意,这包括的字符不仅仅是0-9,还包括罗马数字(例如Ⅲ)或分数(例如⅒)。如果你只想检查0-9,你可以像以前一样做(是UTF-8安全的):

if rune >= 48 && rune <= 57 { ... }

或者

if rune >= '0' && rune <= '9' { ... } // 如Martin Gallagher所建议的

对于字母,unicode包也有类似的函数:func IsLetter(r rune) bool

英文:

You can always use func IsNumber(r rune) bool in the unicode package:

if unicode.IsNumber(rune) { ... }

Just be aware that this includes more characters than just 0-9, such as roman numbers (eg. Ⅲ) or fractions (eg. ⅒) . If you specifically only want to check 0-9, you should instead do like you've done in the past (yes, it is UTF-8 safe):

if rune &gt;= 48 &amp;&amp; rune &lt;= 57 { ... }

or

if rune &gt;= &#39;0&#39; &amp;&amp; rune &lt;= &#39;9&#39; { ... } // as suggested by Martin Gallagher

For letters, the unicode package has a similar function: func IsLetter(r rune) bool

huangapple
  • 本文由 发表于 2014年1月3日 22:23:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/20905750.html
匿名

发表评论

匿名网友

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

确定