Uppercase first letter in NSString

Nielsou Hacken-Bergen picture Nielsou Hacken-Bergen · Sep 9, 2011 · Viewed 48.1k times · Source

How can I uppercase the fisrt letter of a NSString, and removing any accents ?

For instance, Àlter, Alter, alter should become Alter.

But, /lter, )lter, :lter should remains the same, as the first character is not a letter.

Answer

Please Do NOT use this method. Because one letter may have different count in different language. You can check dreamlax answer for that. But I'm sure that You would learn something from my answer. Happy coding :)

NSString *capitalisedSentence = nil;

//Does the string live in memory and does it have at least one letter?
if (yourString && yourString.length > 0) {
    // Yes, it does.

     capitalisedSentence = [yourString stringByReplacingCharactersInRange:NSMakeRange(0,1)
                                                               withString:[[yourString substringToIndex:1] capitalizedString]];
} else {
    // No, it doesn't.
}

Why should I care about the number of letters?

If you try to access (e.g NSMakeRange, substringToIndex etc) the first character in an empty string like @"", then your app will crash. To avoid this you must verify that it exists before processing on it.

What if my string was nil?

Mr.Nil: I'm 'nil'. I can digest anything that you send to me. I won't allow your app to crash all by itself. ;)

Animation of a person swallowing fake explosives, it going off in his stomach, and then smoke coming from his mouth in a cartoonish fashion without injury.

nil will observe any method call you send to it.

So it will digest anything you try on it, nil is your friend.