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*) stringWithSentenceCapitalization
{
NSString *firstCharacterInString = [[self substringToIndex:1] capitalizedString];
NSString *sentenceString = [self stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: firstCharacterInString];
return sentenceString;
}
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:
-(NSString*)stringWithSentenceCapitalization:(NSString*)str
{
// 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.
You can do this in one line this way :
+(NSString *) stringWithSentenceCapitalization:(NSString *)string{
return [NSString stringWithFormat:@”%@%@”,[[string substringToIndex:1] capitalizedString],[string substringFromIndex:1]];
}
Thanks, this is pretty nifty. Short, sweet and to the point. Even though its compact, its still easy to read.
Just stumbled across this while looking for a good solution to the same problem.
Using djleop’s offering, but have added a check for an empty string to avoid an out of bounds exception