Capitalize or change case of an NSString in Objective-C

前端 未结 3 1296
梦毁少年i
梦毁少年i 2020-12-07 09:17

I was wondering how to capitalize a string found in an object in an NSMutableArray.

An NSArray contains the string \'April\' a

相关标签:
3条回答
  • 2020-12-07 09:53

    In case anyone needed the above in swift :

    SWIFT 3.0 and above :

    this will capitalize your string, make the first letter capital :

    viewNoteDateMonth.text  = yourString.capitalized
    

    this will uppercase your string, make all the string upper case :

    viewNoteDateMonth.text  = yourString.uppercased()
    
    0 讨论(0)
  • 2020-12-07 10:03
    viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];
    

    Documentation: http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/uppercaseString

    You can also use lowercaseString and capitalizedString

    0 讨论(0)
  • 2020-12-07 10:12

    Here ya go:

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

    Btw:
    "april" is lowercase ➔ [NSString lowercaseString]
    "APRIL" is UPPERCASE ➔ [NSString uppercaseString]
    "April May" is Capitalized/Word Caps ➔ [NSString capitalizedString]
    "April may" is Sentence caps(method missing; see workaround below)

    Hence what you want is called "uppercase", not "capitalized". ;)

    As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

    @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
    
    0 讨论(0)
提交回复
热议问题