Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Foundation Framework

NSString and NSMutableString

Work with text in Objective-C - string literals, formatting, comparing, searching, substrings, splitting and joining, NSMutableString, Unicode and why NSString length is not always what you expect.

Text is the most common thing a program handles, and in Objective-C that means NSString. Unlike a C char *, an NSString is an object: it knows its length, stores Unicode text, is safe to pass around, and responds to dozens of methods. NSString is immutable: once created, it never changes. When you need to edit text in place, you use its subclass NSMutableString.

This lesson covers the operations you will use daily. All snippets are Objective-C and read-only here, and the runnable examples are C stand-ins that show how the same logic works at the byte level.

Creating strings

OBJECTIVEC
NSString *literal = @"Hello";                                   // compile-time literal
NSString *formatted = [NSString stringWithFormat:@"%@ #%d (%.2f)", literal, 7, 3.14159];
NSString *fromC = [NSString stringWithUTF8String:"from a C string"];
NSString *empty = @"";

The @"..." literal is an NSString, not a C string. Never confuse "abc" (a char *) with @"abc". The %@ format specifier prints any object by sending it description.

Length, comparison and equality

OBJECTIVEC
NSUInteger n = [literal length];                  // 5
BOOL same = [literal isEqualToString:@"Hello"];    // YES

Never compare strings with ==. That compares pointers, which may or may not be the same object. Use isEqualToString: for equality, or compare: for ordering:

OBJECTIVEC
NSComparisonResult r = [@"apple" compare:@"banana"];   // NSOrderedAscending
r = [@"Apple" caseInsensitiveCompare:@"apple"];        // NSOrderedSame
r = [@"file10" compare:@"file9" options:NSNumericSearch]; // NSOrderedDescending (10 > 9)

Searching and substrings

OBJECTIVEC
NSString *path = @"/users/ada/notes.txt";

BOOL hasPrefix = [path hasPrefix:@"/users"];                 // YES
BOOL hasSuffix = [path hasSuffix:@".txt"];                   // YES
NSRange found = [path rangeOfString:@"ada"];                 // {7, 3}
if (found.location != NSNotFound) {
    NSString *name = [path substringWithRange:found];        // "ada"
}
NSString *tail = [path substringFromIndex:7];                // "ada/notes.txt"
NSString *head = [path substringToIndex:6];                  // "/users"
BOOL has = [path containsString:@"notes"];                   // YES

NSRange is a struct {location, length}. A failed search returns location == NSNotFound, so always check before using the range.

Transforming

OBJECTIVEC
[@"hello" uppercaseString];                                  // @"HELLO"
[@"Hello World" lowercaseString];                            // @"hello world"
[@"hello world" capitalizedString];                          // @"Hello World"
[@"a-b-c" stringByReplacingOccurrencesOfString:@"-" withString:@"+"];  // @"a+b+c"
[@"  padded \n" stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  // @"padded"
[@"x" stringByAppendingString:@"y"];                         // @"xy"
[@"photo" stringByAppendingPathExtension:@"png"];            // @"photo.png"

Every one of these returns a new string; the original is untouched.

Splitting and joining

OBJECTIVEC
NSArray *parts = [@"red,green,blue" componentsSeparatedByString:@","];   // 3 strings
NSString *joined = [parts componentsJoinedByString:@" | "];               // @"red | green | blue"

Numbers from strings

OBJECTIVEC
int i = [@"42" intValue];              // 42  (0 if it cannot parse)
double d = [@"3.5" doubleValue];       // 3.5
NSInteger big = [@"9000000000" integerValue];

These return 0 on failure, so you cannot tell "0" from "not a number". For validation use NSNumberFormatter or NSScanner.

NSMutableString

OBJECTIVEC
NSMutableString *log = [NSMutableString stringWithString:@"Start"];
[log appendString:@" -> step 1"];
[log appendFormat:@" -> step %d", 2];
[log insertString:@">> " atIndex:0];
[log replaceCharactersInRange:NSMakeRange(0, 2) withString:@"##"];
[log deleteCharactersInRange:NSMakeRange(0, 3)];
NSString *snapshot = [log copy];        // immutable copy

Use a mutable string when you build a long string in a loop. Repeated stringByAppendingString: creates a new object each time. Remember that a property holding a string should be copy, because someone could hand you an NSMutableString (see property attributes).

Unicode: length is not bytes

NSString stores UTF-16 code units. length counts those units, which is neither bytes nor "characters the reader sees". The emoji @"๐Ÿ™‚" has length == 2, and a letter followed by a combining accent can be two units that look like one character. To step through visible characters, use enumerateSubstringsInRange:options:usingBlock: with NSStringEnumerationByComposedCharacterSequences. To get bytes, convert explicitly:

OBJECTIVEC
NSData *bytes = [@"cafรฉ" dataUsingEncoding:NSUTF8StringEncoding];   // 5 bytes: c a f 0xC3 0xA9
NSUInteger byteCount = [@"cafรฉ" lengthOfBytesUsingEncoding:NSUTF8StringEncoding];  // 5
NSUInteger units = [@"cafรฉ" length];                                  // 4

A byte-level model

In C, a string is a null-terminated array of bytes, so you handle all of this yourself. The stand-in below shows an immutable-by-convention string operation (replace returns a new string), a mutable buffer with append, and why UTF-8 byte count differs from character count.

C Stand-in: strings as bytes - immutable vs mutable, bytes vs characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The second example shows the idea behind NSMutableString's appendString:: a buffer with spare capacity, so appending is cheap on average.

Formatting numbers and dates for people

Use NSNumberFormatter and NSDateFormatter (see numbers and dates) rather than stringWithFormat: when the text is for display, because they honor the user's locale.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How should you test whether two NSStrings have the same text?

    == compares pointers; isEqualToString: compares contents.
  2. 2. What does [path rangeOfString:@"zzz"] return when there is no match?

    NSRange is a struct, so a miss is signalled with location == NSNotFound.
  3. 3. Which is the right way to build a large string in a loop?

    A mutable string appends in place and avoids creating a new object per step.
  4. 4. What does [@"๐Ÿ™‚" length] return?

    length counts UTF-16 code units, and this emoji needs a surrogate pair of two units.
  5. 5. Which property attribute suits an NSString?

    copy protects against a caller later mutating an NSMutableString you were given.

Summary

  • NSString is an immutable Unicode string object; @"..." makes one.
  • Compare with isEqualToString: or compare:, never ==.
  • Searches return NSRange; check for NSNotFound.
  • Use NSMutableString to build text; length counts UTF-16 units, not bytes or visible characters.

Next: NSArray, NSDictionary and NSSet