String Functions in Objective-C

The standard library’s NSString class provides many useful string-related methods. Here are some examples to give you a sense of the class.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // We define a helper function to print results
        void (^p)(NSString *) = ^(NSString *s) {
            NSLog(@"%@", s);
        };
        
        // Here's a sample of the methods available in NSString
        p([NSString stringWithFormat:@"Contains:  %@", [@"test" containsString:@"es"] ? @"YES" : @"NO"]);
        p([NSString stringWithFormat:@"Count:     %lu", (unsigned long)[@"test" componentsSeparatedByString:@"t"].count - 1]);
        p([NSString stringWithFormat:@"HasPrefix: %@", [@"test" hasPrefix:@"te"] ? @"YES" : @"NO"]);
        p([NSString stringWithFormat:@"HasSuffix: %@", [@"test" hasSuffix:@"st"] ? @"YES" : @"NO"]);
        p([NSString stringWithFormat:@"Index:     %lu", (unsigned long)[@"test" rangeOfString:@"e"].location]);
        p([NSString stringWithFormat:@"Join:      %@", [@[@"a", @"b"] componentsJoinedByString:@"-"]]);
        p([NSString stringWithFormat:@"Repeat:    %@", [@"a" stringByPaddingToLength:5 withString:@"a" startingAtIndex:0]]);
        p([NSString stringWithFormat:@"Replace:   %@", [@"foo" stringByReplacingOccurrencesOfString:@"o" withString:@"0"]]);
        p([NSString stringWithFormat:@"Replace:   %@", [@"foo" stringByReplacingOccurrencesOfString:@"o" withString:@"0" options:0 range:NSMakeRange(0, 2)]]);
        p([NSString stringWithFormat:@"Split:     %@", [@"a-b-c-d-e" componentsSeparatedByString:@"-"]]);
        p([NSString stringWithFormat:@"ToLower:   %@", [@"TEST" lowercaseString]]);
        p([NSString stringWithFormat:@"ToUpper:   %@", [@"test" uppercaseString]]);
    }
    return 0;
}

To run this program, save it as StringFunctions.m and compile it with:

$ clang -framework Foundation StringFunctions.m -o StringFunctions
$ ./StringFunctions

The output will be:

Contains:  YES
Count:     2
HasPrefix: YES
HasSuffix: YES
Index:     1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     (
    a,
    b,
    c,
    d,
    e
)
ToLower:   test
ToUpper:   TEST

In Objective-C, string operations are mostly performed using methods on NSString objects. Some key differences from other languages:

  1. Objective-C uses NSString instead of a primitive string type.
  2. Many operations are methods on NSString rather than standalone functions.
  3. Some operations, like Count, require a bit more work in Objective-C.
  4. Objective-C uses YES and NO for boolean values instead of true and false.

These examples demonstrate some of the common string operations in Objective-C. You can find more methods in the NSString class documentation.