How to check if my string starts with an uppercase character

I am working with cocoa on an iPhone and I am looking for some method like:

NSString *s = @"Hello"; [s isStringStartsWithUpperCaseCharacter] -(BOOL) isStringStartsWithUpperCaseCharacter; 

The first letter of the string may not be an ASCII letter, for example: Á , Γ‡ , Ê ...

Is there any way that can help me?

I saw in the documentation that there are some methods for converting a string to upper and lower case, but there are no methods to ask if the string is lowercase or uppercase .

+4
source share
5 answers
 BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:0]]; 

Edit:

I'm not sure what the difference is between uppercaseLetterCharacterSet and capitalizedLetterCharacterSet . If someone finds out, leave a comment!

2nd Edit:

Thanks, Ole Begemann, for learning about the differences. I edited the code to make it work properly.

+26
source
 return [myString rangeOfCharacterFromSet: [NSCharacterSet uppercaseLetterCharacterSet]].location==0; 

This should work, but it is an expensive way to solve this problem.

+1
source

I don't know Objective-C yet, but you can put the first character on another line and "toupper" is ... then compare it with the first character of the original string .. if they are equal, the first character is uppercase.

-one
source

First of all, if you just want to capitalize the first character, try

 - (NSString *)capitalizedString; 

Otherwise, you can use something like

 NSString *firstCharacter = [s substringWithRange:NSMakeRange(0,1)]; if (firstCharacter != nil && [firstCharacter isEqualToString:[firstCharacter uppercaseString]]) { //first character was capitalized } else { //first character was lowercase } 
-one
source

Here, Nikolai’s answer is placed in a block.

 BOOL (^startsWithUppercase)(NSString *) = ^(NSString *string) { return [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[string characterAtIndex:0]]; }; 

Name it as follows:

 NSString *name = @"Mark"; if (startsWithUppercase(name)) { // do something } 

Another option is to put it in a category in an NSString.

-one
source

All Articles