简体   繁体   中英

How to check if my string starts with uppercase character

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 .

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.

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

这应该有效,但这是解决这个问题的一种昂贵的方法。

我还不知道Objective-C但你可以将第一个字符放在另一个字符串中并“toupper”它...然后将它与原始字符串的第一个字符进行比较..如果它们相等,则第一个字符是大写。

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM