Objective-C中如何将句子的第一个单词大写?

发布于 2024-08-25 15:06:39 字数 170 浏览 6 评论 0原文

我已经找到了如何将句子中的所有单词大写,但不仅仅是第一个单词。

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

我不想更改为小写并将第一个字符大写。我只想将第一个单词大写,而不改变其他单词。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

并安 2024-09-01 15:06:39

这是另一种尝试:

NSString *txt = @"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];

对于 Swift 语言:

txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)

Here is another go at it:

NSString *txt = @"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];

For Swift language:

txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)
苏辞 2024-09-01 15:06:39

接受的答案是错误的。首先,将 NSString 的单位视为用户期望的“字符”是不正确的。有代理对。有组合序列。拆分它们会产生不正确的结果。其次,大写第一个字符不一定会产生与大写包含该字符的单词相同的结果。语言可以是上下文相关的。

正确的方法是让框架以适合语言环境的方式识别单词(可能还有句子)。并且还要以适合区域设置的方式利用大写。

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

字符串的第一个单词可能与字符串第一个句子的第一个单词不同。要识别字符串的第一个(或每个)句子,然后将其第一个单词大写,然后使用 -enumerateSubstringsInRange:options:usingBlock: 的外部调用将上面的内容括起来代码>NSStringEnumerationBySentences | NSStringEnumerationLocalized。在内部调用中,传递外部调用提供的 substringRange 作为范围参数。

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.

呆头 2024-09-01 15:06:39

使用

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

数组中的第一个对象并将其大写,然后使用

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

将它们连接回来

Use

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

and capitalize the first object in the array and then use

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

to join them back

小帐篷 2024-09-01 15:06:39
pString = [pString
           stringByReplacingCharactersInRange:NSMakeRange(0,1)
           withString:[[pString substringToIndex:1] capitalizedString]];
pString = [pString
           stringByReplacingCharactersInRange:NSMakeRange(0,1)
           withString:[[pString substringToIndex:1] capitalizedString]];
揽月 2024-09-01 15:06:39

您可以使用正则表达式进行用户操作,我已经完成了,这对我来说很简单,您可以粘贴下面的代码
+(NSString*)CaptializeFirstCharacterOfSentence:(NSString*)句子{

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;

}
//调用这个方法
NsString *resultSentence = [UserClass CaptializeFirstCharacterOfSentence:yourTexthere];

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

允世 2024-09-01 15:06:39

Swift 中的替代解决方案:

var str = "hello"

if count(str) > 0 {
    str.splice(String(str.removeAtIndex(str.startIndex)).uppercaseString, atIndex: str.startIndex)
}

An alternative solution in Swift:

var str = "hello"

if count(str) > 0 {
    str.splice(String(str.removeAtIndex(str.startIndex)).uppercaseString, atIndex: str.startIndex)
}
卷耳 2024-09-01 15:06:39

为了有选择,我建议:

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

我在工作,没有 Mac 来测试这个,但如果我没记错的话,你不能使用 [myString cStringUsingEncoding:NSUTF8StringEncoding]< /code> 因为它返回一个 const char *

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

伪装你 2024-09-01 15:06:39

快速地,您可以使用此扩展来执行以下操作:

extension String {
    func ucfirst() -> String {
        return (self as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: (self as NSString).substringToIndex(1).uppercaseString)
    }    
}

像这样调用您的字符串:

var ucfirstString:String = "test".ucfirst()

In swift you can do it as followed by using this extension:

extension String {
    func ucfirst() -> String {
        return (self as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: (self as NSString).substringToIndex(1).uppercaseString)
    }    
}

calling your string like this:

var ucfirstString:String = "test".ucfirst()
迷迭香的记忆 2024-09-01 15:06:39

我知道这个问题专门要求 Objective C 答案,但是这里有一个针对 Swift 2.0 的解决方案:

let txt = "hi my friends!"
var sentencecaseString = ""

for (index, character) in txt.characters.enumerate() {
    if 0 == index {
        sentencecaseString += String(character).uppercaseString
    } else {
        sentencecaseString.append(character)
    }
}

或者作为扩展:

func sentencecaseString() -> String {
    var sentencecaseString = ""
    for (index, character) in self.characters.enumerate() {
        if 0 == index {
            sentencecaseString += String(character).uppercaseString
        } else {
            sentencecaseString.append(character)
        }
    }
    return sentencecaseString
}

I know the question asks specifically for an Objective C answer, however here is a solution for Swift 2.0:

let txt = "hi my friends!"
var sentencecaseString = ""

for (index, character) in txt.characters.enumerate() {
    if 0 == index {
        sentencecaseString += String(character).uppercaseString
    } else {
        sentencecaseString.append(character)
    }
}

Or as an extension:

func sentencecaseString() -> String {
    var sentencecaseString = ""
    for (index, character) in self.characters.enumerate() {
        if 0 == index {
            sentencecaseString += String(character).uppercaseString
        } else {
            sentencecaseString.append(character)
        }
    }
    return sentencecaseString
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文