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

后端 未结 9 516
青春惊慌失措
青春惊慌失措 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:55

    The accepted answer is wrong. First, it is not correct to treat the units of NSString as "characters" in the sense that a user expects. There are surrogate pairs. There are combining sequences. Splitting those will produce incorrect results. Second, it is not necessarily the case that uppercasing the first character produces the same result as capitalizing a word containing that character. Languages can be context-sensitive.

    The correct way to do this is to get the frameworks to identify words (and possibly sentences) in the locale-appropriate manner. And also to capitalize in the locale-appropriate manner.

    [aMutableString enumerateSubstringsInRange:NSMakeRange(0, [aMutableString length])
                                       options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                                    usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [aMutableString replaceCharactersInRange:substringRange
                                      withString:[substring capitalizedStringWithLocale:[NSLocale currentLocale]]];
        *stop = YES;
    }];
    

    It's possible that the first word of a string is not the same as the first word of the first sentence of a string. To identify the first (or each) sentence of the string and then capitalize the first word of that (or those), then surround the above in an outer invocation of -enumerateSubstringsInRange:options:usingBlock: using NSStringEnumerationBySentences | NSStringEnumerationLocalized. In the inner invocation, pass the substringRange provided by the outer invocation as the range argument.

提交回复
热议问题