Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to set a single character of an NSString to uppercase

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.

like image 999
Rog Avatar asked May 19 '09 16:05

Rog


1 Answers

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

 NSString *capitalisedSentence = 
    [dateString stringByReplacingCharactersInRange:NSMakeRange(0,1)  
    withString:[[dateString  substringToIndex:1] capitalizedString]];
like image 184
doomspork Avatar answered Nov 14 '22 08:11

doomspork