views:

2057

answers:

2

I would like to change the first character of an NSString to uppercase. Unfortunately, - (NSString *)capitalizedString converts the first letter of every word to uppercase. Is there an easy way to convert just a single character to uppercase?

I'm currently using:

NSRange firstCharRange = NSMakeRange(0,1);
NSString* firstCharacter = [dateString substringWithRange:firstCharRange];
NSString* uppercaseFirstChar = [firstCharacter originalString];
NSMutableString* capitalisedSentence = [originalString mutableCopy];
[capitalisedSentence replaceCharactersInRange:firstCharRange withString:uppercaseFirstChar];

Which seems a little convoluted but at least makes no assumptions about the encoding of the underlying unicode string.

+2  A: 

Since NSString is immutable, what you have seems to be a good way to do what you want to do. The implementations of (NSString*)uppercaseString and similar methods probably look very much like what you've written, as they return a new NSString instead of modifying the one you sent the message to.

One other thing: in your question I think you meant to say that the method (NSString*)capitalizedString converts the first letter of every word to uppercase.

Jared Oberhaus
Thanks for the typo.
Roger Nolan
+4  A: 

Very similar approach to what you have but a little more condense:

 NSString *capitalisedSentence = 
    [dateString stringByReplacingCharactersInRange:NSMakeRange(0,1)  
    withString:[[dateString  substringToIndex:1] capitalizedString]];
Doomspork
yeah, optimised for cr/lf ;-) I like to let the optimiser take my temporaries out.
Roger Nolan