views:

654

answers:

3

I've already found how to capitalize all words of the sentence, but not the first word only.

NSString *txt =@"hi my friends!"
[txt capitalizedString];

I don't want to change to lower case and capitalize the first char. I'd like to capitalize the first word only without change the others.

+5  A: 

Use

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

and capitalize the first object in the array and then use

- (NSString *)componentsJoinedByString:(NSString *)separator

to join them back

Tuomas Pelkonen
I am pretty alien to Objective-c, but you have to do so much to just capitalize the word??
Teja Kantamneni
Yes, to capitalize the first word only. Unfortunately, Objective-C is not like Python where every operation can be done on one line.
Tuomas Pelkonen
@Teja: NSString does not natively support doing something to just one "word" in a string, and it's quite a verbose language anyway, so yes.
Chuck
Thanks too......
wal
A: 

For the sake of having options, I'd suggest:

NSString *myString = [NSString stringWithFormat:@"this is a string..."];

char *tmpStr = calloc([myString length] + 1,sizeof(char));

[myString getCString:tmpStr maxLength:[myString length] + 1 encoding:NSUTF8StringEncoding];

int sIndex = 0;

/* skip non-alpha characters at beginning of string */
while (!isalpha(tmpStr[sIndex])) {
    sIndex++;
}

toupper(tmpStr[sIndex]);

myString = [NSString stringWithCString:tmpStr encoding:NSUTF8StringEncoding];

I'm at work and don't have my Mac to test this on, but if I remember correctly, you couldn't use [myString cStringUsingEncoding:NSUTF8StringEncoding] because it returns a const char *.

alesplin
+3  A: 

Here is another go at it:

NSString *txt = @"hi my friends!"
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];
Johan Kool
It's works perfectly!!!!!!!!!! Tks
wal
Just make sure that the string is always at least 1 character long, or that you are ready to handle the exception thrown when that's not the case.
Johan Kool