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

后端 未结 9 630
青春惊慌失措
青春惊慌失措 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条回答
  •  Happy的楠姐
    2021-01-30 09:46

    you can user with regular expression i have done it's works for me simple you can paste below code +(NSString*)CaptializeFirstCharacterOfSentence:(NSString*)sentence{

    NSMutableString *firstCharacter = [sentence mutableCopy];
    NSString *pattern = @"(^|\\.|\\?|\\!)\\s*(\\p{Letter})";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
    [regex enumerateMatchesInString:sentence options:0 range:NSMakeRange(0, [sentence length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        //NSLog(@"%@", result);
        NSRange r = [result rangeAtIndex:2];
        [firstCharacter replaceCharactersInRange:r withString:[[sentence substringWithRange:r] uppercaseString]];
    }];
    NSLog(@"%@", firstCharacter);
    return firstCharacter;
    

    } //Call this method NsString *resultSentence = [UserClass CaptializeFirstCharacterOfSentence:yourTexthere];

提交回复
热议问题