How to determine if the first character of a NSString is a letter

荒凉一梦 提交于 2019-11-30 00:17:26
rmaddy

First off, your line:

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
}

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
}

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
}        
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!