Reputation: 83
I'm working with cocoa on the iPhone and I'm looking for some method like:
NSString *s = @"Hello";
[s isStringStartsWithUpperCaseCharacter]
-(BOOL) isStringStartsWithUpperCaseCharacter;
The first letter of the string may be non ASCII letter like: Á
, Ç
, Ê
...
Is there some method which can helps me?
I saw in the documentation that there are some methods to convert the string to uppercase and to lowercase but there are no methods for ask if the string is lowercase
or uppercase
.
Upvotes: 5
Views: 6984
Reputation: 37113
Here's Nikolai's answer put into a block.
BOOL (^startsWithUppercase)(NSString *) = ^(NSString *string) {
return [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[string characterAtIndex:0]];
};
Call it like this:
NSString *name = @"Mark";
if (startsWithUppercase(name)) {
// do something
}
Another option would be to put it into a category on NSString.
Upvotes: -1
Reputation:
return [myString rangeOfCharacterFromSet: [NSCharacterSet uppercaseLetterCharacterSet]].location==0;
This should work, but it is a costly way to solve this problem.
Upvotes: 1
Reputation: 81868
BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:0]];
Edit:
I'm not sure what's the difference between uppercaseLetterCharacterSet
and capitalizedLetterCharacterSet
. If someone finds out, please leave a comment!
2nd Edit:
Thanks, Ole Begemann, for finding out about the differences. I edited the code to make it work as expected.
Upvotes: 28
Reputation: 12107
first of all, if you just want to make the first character capitalized, 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
}
Upvotes: -1
Reputation: 9186
I don't know Objective-C yet but you can put the first character in another string and "toupper" it... then compare it to the first character of the original string.. if they're equal, the first character is upper case.
Upvotes: -1