Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

In my app

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]; 

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?

like image 742
iOS dev Avatar asked May 31 '13 14:05

iOS dev


People also ask

How do I find the first character of a string in Objective C?

You want: NSString *firstLetter = [codeString substringToIndex:1];

What is NSString in objective c?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What is a NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


1 Answers

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 }         
like image 99
rmaddy Avatar answered Sep 22 '22 12:09

rmaddy