Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make first letter of NSString Capital in iPhone dev

Tags:

iphone

I am having a NSString to which I am trimming at the start and end for blank spaces. Now I want to make the first alphabet or letter of the string to appear as capital.

Is there any short available or I need to take the first alphabet and convert it to capital on my own.

tnx.

like image 319
rkb Avatar asked Jul 28 '09 18:07

rkb


People also ask

How do you get the first letter of a string Capital?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize the first letter of a string in Objective C?

Just use the capitalizedString method. A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.

How do you make the first character in uppercase in Swift?

To convert a String to Uppercase in Swift, use String. uppercased() function.


2 Answers

You have to do it by hand. This is one of those things that has been built into categories so often by so many people that Apple probably doesn't dare add it as an actual method since it would generate category collisions.

NSString *firstCapChar = [[string substringToIndex:1] capitalizedString];
NSString *cappedString = [string stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];

There are of course many other solutions using NSMutableString or any other way you like to do it using unichar or whatever.

like image 145
Rob Napier Avatar answered Nov 09 '22 23:11

Rob Napier


- (NSString *)capitalizedString

will make all words in the string initially capitalized. If you only have one or two words in your string, this may be what you want.

Here is the NSString class reference.

like image 23
Brian Ramsay Avatar answered Nov 09 '22 22:11

Brian Ramsay