简体   繁体   中英

Uppercase first letter in NSString

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.

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. Happy coding :)

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 (eg 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. ;)

一个人吞咽假爆炸物的动画,它在他的肚子里熄灭,然后以卡通的方式从他的嘴里冒出来而没有受伤。

nil will observe any method call you send to it.

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

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

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 decomposedStringWithCanonicalMapping to 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, eg ":" 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 :)

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

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

@property(readonly, copy) NSString *localizedCapitalizedString;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM