在Objective-C中大写或更改NSString的大小写


140

我想知道如何大写在一个对象中找到的字符串NSMutableArray

一个NSArray包含字符串'April'索引2.
我想这是改变'APRIL'

有这样简单的东西吗?

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] capitalized];

Answers:


391

来吧:

viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];

顺便说一句:
"april"lowercase[NSString lowercaseString]
"APRIL"UPPERCASE[NSString uppercaseString]
"April May"Capitalized/Word Caps[NSString capitalizedString]
"April may"Sentence caps(方法缺失;请参见下面的解决方法)

因此,您想要的是“ 大写 ”,而不是“ 大写 ”。;)

至于“句子上限”,必须记住通常“句子”的意思是“整个字符串”。如果您希望使用真实句子,请使用下面的第二种方法,否则使用第一种方法:

@interface NSString ()

- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences

@end

@implementation NSString

- (NSString *)sentenceCapitalizedString {
    if (![self length]) {
        return [NSString string];
    }
    NSString *uppercase = [[self substringToIndex:1] uppercaseString];
    NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
    return [uppercase stringByAppendingString:lowercase];
}

- (NSString *)realSentenceCapitalizedString {
    __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationBySentences
                          usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
        [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
    }];
    return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}

@end


1

如果有人迅速需要以上内容:

SWIFT 3.0及更高版本:

这将大写您的字符串,使首字母大写:

viewNoteDateMonth.text  = yourString.capitalized

这将大写您的字符串,使所有字符串大写:

viewNoteDateMonth.text  = yourString.uppercased()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.