如何确定NSString的第一个字符是否为字母 [英] How to determine if the first character of a NSString is a letter
问题描述
在我的应用中
我需要知道字符串的第一个字符是否是字母
i need to know if the first character of a string is a letter or not
我正在得到这样的字符串的第一个字符
Im getting first character of the string like this
NSString *codeString;
NSString *firstLetter = [codeString substringFromIndex:1];
我可以通过与a,b,c,.**进行比较来了解它.
I can know it by comparing with a, b, c, .**.
if([firstLetter isEqualToString "a"] || ([firstLetter isEqualToString "A"] || ([firstLetter isEqualToString "b"] ......)
但是还有其他方法要知道吗?
But is there any other method to know?
我需要为字母和符号显示不同的颜色.
I need to display different colors for letters and symbols.
我如何以简单的方式实现它?
How can i achieve it in simple way?
推荐答案
首先,您的一行:
NSString *firstLetter = [codeString substringFromIndex:1];
没有得到第一个字母.这为您提供了一个新字符串,其中包含除第一个字符以外的所有原始字符串.这与您想要的相反.您想要:
does not get the first letter. This gives you a new string the contains all of the original string EXCEPT the first character. This is the opposite of what you want. You want:
NSString *firstLetter = [codeString substringToIndex:1];
但是有一种更好的方法来查看第一个字符是否是字母.
But there is a better way to see if the first character is a letter or not.
unichar firstChar = [[codeString uppercaseString] characterAtIndex:0];
if (firstChar >= 'A' && firstChar <= 'Z') {
// The first character is a letter from A-Z or a-z
}
但是,由于iOS应用程序可与国际用户打交道,因此仅查找字母A-Z中的字符并不是理想的选择.更好的方法是:
However, since iOS apps deal with international users, it is far from ideal to simply look for the character being in the letters A-Z. A better approach would be:
unichar firstChar = [codeString characterAtIndex:0];
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
if ([letters characterIsMember:firstChar]) {
// The first character is a letter in some alphabet
}
在某些情况下,此操作无法按预期进行. unichar
仅包含16位字符.但是NSString
值实际上可以包含一些32位字符.示例包括许多表情符号字符.因此,这段代码可能会产生误报.理想情况下,您想这样做:
There are a few cases where this doesn't work as expected. unichar
only holds 16-bit characters. But NSString
values can actually have some 32-bit characters in them. Examples include many Emoji characters. So it's possible this code can give a false positive. Ideally you would want to do this:
NSRange first = [codeString rangeOfComposedCharacterSequenceAtIndex:0];
NSRange match = [codeString rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet] options:0 range:first];
if (match.location != NSNotFound) {
// codeString starts with a letter
}
这篇关于如何确定NSString的第一个字符是否为字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!