How to make first letter uppercase in a UILabel?

43,063

Solution 1

If there is only one word String, then use the method

-capitalized

let capitalizedString = myStr.capitalized // capitalizes every word

Otherwise, for multi word strings, you have to extract first character and make only that character upper case.

Solution 2

(2014-07-24: Currently accepted answer is not correct) The question is very specific: Make the first letter uppercase, leave the rest lowercase. Using capitalizedString produces a different result: “Capitalized String” instead of “Capitalized string”. There is another variant depending on the locale, which is capitalizedStringWithLocale, but it's not correct for spanish, right now it's using the same rules as in english, so this is how I'm doing it for spanish:

NSString *abc = @"this is test";

abc = [NSString stringWithFormat:@"%@%@",[[abc substringToIndex:1] uppercaseString],[abc substringFromIndex:1] ];       
NSLog(@"abc = %@",abc);

Solution 3

In case someone is still interested in 2016, here is a Swift 3 extension:

extension String {
    func capitalizedFirst() -> String {
        let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
        let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
        return first.uppercased() + rest.lowercased()
    }

    func capitalizedFirst(with: Locale?) -> String {
        let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
        let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
        return first.uppercased(with: with) + rest.lowercased(with: with)
    }
}

Then you use it exactly as you would for the usual uppercased() or capitalized():

myString.capitalizedFirst() or myString.capitalizedFirst(with: Locale.current)

Solution 4

Simply

- (NSString *)capitalizeFirstLetterOnlyOfString:(NSString *)string{
     NSMutableString *result = [string lowercaseString].mutableCopy;
     [result replaceCharactersInRange:NSMakeRange(0, 1) withString:[[result substringToIndex:1] capitalizedString]];

     return result;
}

Solution 5

This is for your NSString+Util category...

- (NSString *) capitalizedFirstLetter {
    NSString *retVal;
    if (self.length < 2) {
        retVal = self.capitalizedString;
    } else {
        retVal = string(@"%@%@",[[self substringToIndex:1] uppercaseString],[self substringFromIndex:1]);
    }
    return retVal;
}

You can do that with NSString stringWithFormat, of course. I use this weirdness:

#define string(...) \
[NSString stringWithFormat:__VA_ARGS__]
Share:
43,063
HardCode
Author by

HardCode

Updated on July 21, 2022

Comments

  • HardCode
    HardCode almost 2 years

    I'm developing an iPhone app. In a label, I want to show an user's first letter of the name uppercase. How do I do that?