While localizing Weather Vane, I found that the non-English forecasts returned from AccuWeather are always returned with the forecast in all lower case. The English forecast returns a string with the first character in the string capitalized; like a sentence. Makes sense to me, so I thought I’d just find the method in NSString that would do that for me. Well, there isn’t one, so what did I do? Category time! Here’s what I did:
NSString *firstCharacterInString = [[self substringToIndex:1] capitalizedString];
NSString *sentenceString = [self stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: firstCharacterInString];
The only gotcha here, if there is one, is that
(NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
is Leopard (10.5) and above only, so if you need to support 10.4 (as I do), you need to do something else.
Here’s what I did in Weather Vane:
// Get the first character in the string and capitalize it.
NSString *firstCapChar = [[str substringToIndex:1] capitalizedString];
NSMutableString * temp = [str mutableCopy];
// Replace the first character with the capitalized version.
[temp replaceCharactersInRange:NSMakeRange(0, 1) withString:firstCapChar];
return [temp autorelease];
As always, if you find a better way, please let me know.