rkb
rkb

Reputation: 11231

How to make first letter of NSString Capital in iPhone dev

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.

Upvotes: 13

Views: 14300

Answers (3)

fnc12
fnc12

Reputation: 2237

@BrianRamsay answer is good but it makes all words capitalized instead of the first one only. I created a comfortable category for @RobNapier answer:

@interface NSString (Initcap)

@property (readonly) NSString *initcappedString;

@end

@implementation NSString (Initcap)

- (NSString *)initcappedString {
    NSString *firstCapChar = [[self substringToIndex:1] capitalizedString];
    return [self stringByReplacingCharactersInRange:NSMakeRange(0,1)
                                         withString:firstCapChar];
}

@end

Next use it like this str.initcappedString.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299265

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.

Upvotes: 37

Brian Ramsay
Brian Ramsay

Reputation: 7635

- (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.

Upvotes: 7

Related Questions