NSString 中的第一个字母大写

发布于 2024-12-03 11:41:15 字数 252 浏览 0 评论 0原文

如何将 NSString 的第一个字母大写,并删除任何重音符号?

例如,ÀlterAlteralter 应该变成 Alter

但是,/lter)lter:lter 应保持相同,因为第一个字符不是信。

How can I uppercase the fisrt letter of a NSString, and removing any accents ?

For instance, Àlter, Alter, alter should become Alter.

But, /lter, )lter, :lter should remains the same, as the first character is not a letter.

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

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

发布评论

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

评论(7

痴情换悲伤 2024-12-10 11:41:15

请不要使用此方法。因为一个字母在不同的语言中可能有不同的计数。您可以检查 dreamlax 答案。但我确信您会从我的回答中学到一些东西。

NSString *capitalisedSentence = nil;

//Does the string live in memory and does it have at least one letter?
if (yourString && yourString.length > 0) {
    // Yes, it does.
    
     capitalisedSentence = [yourString stringByReplacingCharactersInRange:NSMakeRange(0,1)
                                                               withString:[[yourString substringToIndex:1] capitalizedString]];
} else {
    // No, it doesn't.
}

我为什么要关心字母数量?

如果您尝试访问(例如 NSMakeRangesubstringToIndex 等)
空字符串中的第一个字符,例如 @"",那么您的应用程序将崩溃。为了避免这种情况,您必须在对其进行处理之前验证它是否存在。

如果我的字符串为零怎么办?

Mr.Nil:我是“无”。我可以消化你发送给我的任何内容。我不会允许你的应用程序自行崩溃。 ;)

一个人吞下假炸药的动画,炸药在他的胃里爆炸,然后以卡通风格从他的嘴里冒出烟雾不会造成伤害。

nil 将观察您发送给它的任何方法调用。

所以它会消化你尝试的任何东西,nil 是你的朋友。

Please Do NOT use this method. Because one letter may have different count in different language. You can check dreamlax answer for that. But I'm sure that You would learn something from my answer.

NSString *capitalisedSentence = nil;

//Does the string live in memory and does it have at least one letter?
if (yourString && yourString.length > 0) {
    // Yes, it does.
    
     capitalisedSentence = [yourString stringByReplacingCharactersInRange:NSMakeRange(0,1)
                                                               withString:[[yourString substringToIndex:1] capitalizedString]];
} else {
    // No, it doesn't.
}

Why should I care about the number of letters?

If you try to access (e.g NSMakeRange, substringToIndex etc)
the first character in an empty string like @"", then your app will crash. To avoid this you must verify that it exists before processing on it.

What if my string was nil?

Mr.Nil: I'm 'nil'. I can digest anything that you send to me. I won't allow your app to crash all by itself. ;)

Animation of a person swallowing fake explosives, it going off in his stomach, and then smoke coming from his mouth in a cartoonish fashion without injury.

nil will observe any method call you send to it.

So it will digest anything you try on it, nil is your friend.

我早已燃尽 2024-12-10 11:41:15

由于您想删除变音符号,因此可以使用 此方法与常见的字符串操作方法结合使用,如下所示:

/* create a locale where diacritic marks are not considered important, e.g. US English */
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"] autorelease];

NSString *input = @"Àlter";

/* get first char */
NSString *firstChar = [input substringToIndex:1];

/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:locale];

/* create the new string */
NSString *result = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];

Since you want to remove diacritic marks, you could use this method in combination with the common string manipulating methods, like this:

/* create a locale where diacritic marks are not considered important, e.g. US English */
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"] autorelease];

NSString *input = @"Àlter";

/* get first char */
NSString *firstChar = [input substringToIndex:1];

/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:locale];

/* create the new string */
NSString *result = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];
野心澎湃 2024-12-10 11:41:15

我将列出一个步骤列表,我认为您可以使用这些步骤来完成此任务。希望您能顺利完成! :)

  • 使用 decomposedStringWithCanonicalMapping 分解任何重音符号(重要的是要确保重音字符不会被不必要地删除)
  • 使用characterAtIndex:提取第一个字母(索引0),使用upperCaseString 将其转换为大写字母并使用 stringByReplacingCharactersInRange 将第一个字母替换回原始字符串。
  • 在此步骤中,在将其变为大写之前,您可以检查第一个字母是否是您不想替换的字符之一,例如“:”或“;”,如果是,则不要继续其余的字符的程序。
  • 执行 [theString stringByReplacingOccurrencesOfString:@"" withString:@""]` 类调用以删除剩余的重音符号。

这一切都应该大写你的第一个字母并删除任何重音:)

Gonna drop a list of steps which I think you can use to get this done. Hope you can follow through without a prob! :)

  • Use decomposedStringWithCanonicalMappingto decompose any accents (Important to make sure accented characters aren't just removed unnecessarily)
  • Use characterAtIndex: to extract the first letter (index 0), use upperCaseString to turn it into capitol lettering and use stringByReplacingCharactersInRange to replace the first letter back into the original string.
  • In this step, BEFORE turning it into uppercase, you can check whether the first letter is one of the characters you do not want to replace, e.g. ":" or ";", and if it is, do not follow through with the rest of the procedure.
  • Do a [theString stringByReplacingOccurrencesOfString:@"" withString:@""]` sort of call to remove any accents left over.

This all should both capitalize your first letter AND remove any accents :)

喜爱皱眉﹌ 2024-12-10 11:41:15

从 iOS 9.0 开始,有一种使用当前语言环境将字符串大写的方法:

@property(readonly, copy) NSString *localizedCapitalizedString;

Since iOS 9.0 there is a method to capitalize string using current locale:

@property(readonly, copy) NSString *localizedCapitalizedString;
守护在此方 2024-12-10 11:41:15

我在类似的情况下使用此方法,但我不确定问题是否要求将其他字母小写。

- (NSString *)capitalizedOnlyFirstLetter {

    if (self.length < 1) {
        return @"";
    }
    else if (self.length == 1) {
        return [self capitalizedString];
    }
    else {

        NSString *firstChar = [self substringToIndex:1];
        NSString *otherChars = [self substringWithRange:NSMakeRange(1, self.length - 1)];

        return [NSString stringWithFormat:@"%@%@", [firstChar uppercaseString], [otherChars lowercaseString]];
    }
}

I'm using this method for similar situations but I'm not sure if question asked to make other letters lowercase.

- (NSString *)capitalizedOnlyFirstLetter {

    if (self.length < 1) {
        return @"";
    }
    else if (self.length == 1) {
        return [self capitalizedString];
    }
    else {

        NSString *firstChar = [self substringToIndex:1];
        NSString *otherChars = [self substringWithRange:NSMakeRange(1, self.length - 1)];

        return [NSString stringWithFormat:@"%@%@", [firstChar uppercaseString], [otherChars lowercaseString]];
    }
}
赠我空喜 2024-12-10 11:41:15

只是为了添加一些选项,我使用此类别将 NSString 的第一个字母大写。

@interface NSString (CapitalizeFirst)
    - (NSString *)capitalizeFirst;
    - (NSString *)removeDiacritic;
@end

@implementation NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst {
    if ( self.length <= 1 ) {
        return [self uppercaseString];
    }
    else {
        return [[[[self substringToIndex:1] removeDiacritic] uppercaseString] stringByAppendingString:[[self substringFromIndex:1] removeDiacritic]];
        // Or: return [NSString stringWithFormat:@"%@%@", [[[self substringToIndex:1] removeDiacritic] uppercaseString], [[self substringFromIndex:1] removeDiacritic]];
    }
}

- (NSString *)removeDiacritic { // Taken from: http://stackoverflow.com/a/10932536/1986221
    NSData *data = [NSData dataUsingEncoding:NSASCIIStringEncoding
                       allowsLossyConversion:YES];
    return [[NSString alloc] initWithData:data
                                 encoding:NSASCIIStringEncoding];
}
@end

然后你可以简单地调用:

NSString *helloWorld  = @"hello world";
NSString *capitalized = [helloWorld capitalizeFirst];
NSLog(@"%@ - %@", helloWorld, capitalized);

Just for adding some options, I use this category to capitalize the first letter of a NSString.

@interface NSString (CapitalizeFirst)
    - (NSString *)capitalizeFirst;
    - (NSString *)removeDiacritic;
@end

@implementation NSString (CapitalizeFirst)
- (NSString *)capitalizeFirst {
    if ( self.length <= 1 ) {
        return [self uppercaseString];
    }
    else {
        return [[[[self substringToIndex:1] removeDiacritic] uppercaseString] stringByAppendingString:[[self substringFromIndex:1] removeDiacritic]];
        // Or: return [NSString stringWithFormat:@"%@%@", [[[self substringToIndex:1] removeDiacritic] uppercaseString], [[self substringFromIndex:1] removeDiacritic]];
    }
}

- (NSString *)removeDiacritic { // Taken from: http://stackoverflow.com/a/10932536/1986221
    NSData *data = [NSData dataUsingEncoding:NSASCIIStringEncoding
                       allowsLossyConversion:YES];
    return [[NSString alloc] initWithData:data
                                 encoding:NSASCIIStringEncoding];
}
@end

And then you can simply call:

NSString *helloWorld  = @"hello world";
NSString *capitalized = [helloWorld capitalizeFirst];
NSLog(@"%@ - %@", helloWorld, capitalized);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文