How to capitalize the first word of the sentence in Objective-C?

后端 未结 9 663
青春惊慌失措
青春惊慌失措 2021-01-30 08:54

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];
         


        
9条回答
  •  無奈伤痛
    2021-01-30 09:48

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

提交回复
热议问题