Nielsou Hacken-Bergen
Nielsou Hacken-Bergen

Reputation: 2626

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.

Upvotes: 40

Views: 49366

Answers (7)

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.

Upvotes: 120

ASLLOP
ASLLOP

Reputation: 186

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

@property(readonly, copy) NSString *localizedCapitalizedString;

Upvotes: 2

Alejandro Iván
Alejandro Iván

Reputation: 4051

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

Upvotes: 0

Josip B.
Josip B.

Reputation: 2464

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

Upvotes: 1

meaning-matters
meaning-matters

Reputation: 22936

You can use NSString's:

- (NSString *)capitalizedString

or (iOS 6.0 and above):

- (NSString *)capitalizedStringWithLocale:(NSLocale *)locale

Upvotes: 90

Madhu
Madhu

Reputation: 2384

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

Upvotes: 2

dreamlax
dreamlax

Reputation: 95315

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

Upvotes: 55

Related Questions