Capitalize in Objective-C

Published on 03 October 2020 (Updated: 30 April 2026)

Welcome to the Capitalize in Objective-C page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

#import <Foundation/Foundation.h>

@interface NSString (CapitalizeFirst)
- (nullable NSString*)stringByCapitalizingFirstCharacter;
@end

@implementation NSString (CapitalizeFirst)

- (NSString*)stringByCapitalizingFirstCharacter {
    if (self.length == 0) return nil;

    NSRange firstCharRange = [self rangeOfComposedCharacterSequenceAtIndex:0];
    NSString* firstLetter =
        [[self substringWithRange:firstCharRange] uppercaseString];

    return [self stringByReplacingCharactersInRange:firstCharRange
                                         withString:firstLetter];
}

@end

int main(int argc, const char* argv[]) {
    @autoreleasepool {
        NSString* usage = @"Usage: please provide a string";
        NSString* input = argc > 1 ? @(argv[1]) : @"";

        NSString* trimmed =
            [input stringByTrimmingCharactersInSet:
                       NSCharacterSet.whitespaceAndNewlineCharacterSet];

        NSString* result = [trimmed stringByCapitalizingFirstCharacter];

        puts((result ?: usage).UTF8String);
    }

    return 0;
}

Capitalize in Objective-C was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.