英文:
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 >= 48 && rune <= 57 { ... }
or
if rune >= '0' && rune <= '9' { ... } // as suggested by Martin Gallagher
For letters, the unicode package has a similar function: func IsLetter(r rune) bool
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论