NSString
NSString is Foundation's immutable Unicode string. Once created, its text never changes; methods that "modify" a string return a new string instead. (For a string you can change in place, see NSMutableString in the next lesson.)
Creating strings
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *literal = @"Cocoa"; // literal
NSString *formatted = [NSString stringWithFormat:@"%@ %d", @"Version", 3];
NSString *fromC = [NSString stringWithUTF8String:"from a C string"];
NSString *empty = @"";
NSString *repeated = [@"" stringByPaddingToLength:5 withString:@"ab" startingAtIndex:0];
NSLog(@"%@ | %@ | %@", literal, formatted, fromC);
NSLog(@"empty length: %lu", (unsigned long)empty.length);
NSLog(@"repeated: %@", repeated);
NSLog(@"back to C: %s", [literal UTF8String]);
}
return 0;
}Cocoa | Version 3 | from a C string
empty length: 0
repeated: ababa
back to C: Cocoa
stringWithFormat: is the workhorse: it accepts the same specifiers as NSLog and returns the result as a string.
Length, characters and substrings
length counts UTF-16 code units, not user-visible characters. For ordinary Latin text they're the same, but an emoji counts as 2.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *word = @"Objective";
NSLog(@"length: %lu", (unsigned long)word.length);
NSLog(@"first char: %C", [word characterAtIndex:0]);
NSLog(@"first 3: %@", [word substringToIndex:3]);
NSLog(@"from 3: %@", [word substringFromIndex:3]);
NSLog(@"range 2..5: %@", [word substringWithRange:NSMakeRange(2, 4)]);
NSString *emoji = @"Hi 😀";
NSLog(@"'%@' has length %lu", emoji, (unsigned long)emoji.length);
}
return 0;
}length: 9
first char: O
first 3: Obj
from 3: ective
range 2..5: ject
'Hi 😀' has length 5
%C prints a unichar (one UTF-16 code unit). An NSRange is a C struct with a location (start index) and a length.
Comparing strings
Never compare strings with ==, which compares pointers. Use isEqualToString: for equality and compare: for ordering:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *a = @"apple";
NSString *b = [NSString stringWithFormat:@"app%@", @"le"]; // same text, built at run time
NSLog(@"isEqualToString: %d", [a isEqualToString:b]);
NSLog(@"compare apple/banana: %ld", (long)[a compare:@"banana"]);
NSLog(@"case-insensitive: %ld", (long)[@"HELLO" caseInsensitiveCompare:@"hello"]);
NSLog(@"hasPrefix app: %d", [a hasPrefix:@"app"]);
NSLog(@"hasSuffix .png: %d", [@"photo.png" hasSuffix:@".png"]);
NSLog(@"contains 'pl': %d", [a containsString:@"pl"]);
}
return 0;
}isEqualToString: 1
compare apple/banana: -1
case-insensitive: 0
hasPrefix app: 1
hasSuffix .png: 1
contains 'pl': 1
Searching and transforming
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *sentence = @" the quick brown fox ";
NSString *trimmed = [sentence stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"[%@]", trimmed);
NSLog(@"%@", [trimmed uppercaseString]);
NSLog(@"%@", [trimmed capitalizedString]);
NSLog(@"%@", [trimmed stringByReplacingOccurrencesOfString:@"quick" withString:@"lazy"]);
NSRange r = [trimmed rangeOfString:@"brown"];
if (r.location != NSNotFound) {
NSLog(@"'brown' found at %lu, length %lu", (unsigned long)r.location, (unsigned long)r.length);
}
NSRange missing = [trimmed rangeOfString:@"cat"];
NSLog(@"'cat' found? %@", missing.location == NSNotFound ? @"no" : @"yes");
NSArray *words = [trimmed componentsSeparatedByString:@" "];
NSLog(@"%lu words, last: %@", (unsigned long)words.count, words.lastObject);
NSLog(@"joined: %@", [words componentsJoinedByString:@"-"]);
}
return 0;
}[the quick brown fox]
THE QUICK BROWN FOX
The Quick Brown Fox
the lazy brown fox
'brown' found at 10, length 5
'cat' found? no
4 words, last: fox
joined: the-quick-brown-fox
When a search finds nothing, the returned range's location is the special value NSNotFound. Always check for it before using the range.
Converting to and from numbers
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *qty = @"12";
NSString *price = @"4.75";
NSInteger total = [qty integerValue] * 2;
double cost = [qty intValue] * [price doubleValue];
NSLog(@"total %ld, cost %.2f", (long)total, cost);
NSLog(@"'abc' as int: %d", [@"abc" intValue]); // no number: 0
NSLog(@"'42px' as int: %d", [@"42px" intValue]); // reads the leading digits
NSLog(@"'yes' as bool: %d", [@"yes" boolValue]);
NSString *back = [NSString stringWithFormat:@"%ld", (long)total];
NSLog(@"back to string: %@ (length %lu)", back, (unsigned long)back.length);
}
return 0;
}total 24, cost 57.00
'abc' as int: 0
'42px' as int: 42
'yes' as bool: 1
back to string: 24 (length 2)
Note:
intValuereturns0both for@"0"and for text that isn't a number, so it can't tell you whether parsing succeeded. When the difference matters, useNSScanneror check the text first.
Common methods
| Method | Result |
|---|---|
length |
number of UTF-16 units |
isEqualToString: |
YES if the same text |
hasPrefix: / hasSuffix: / containsString: |
substring tests |
rangeOfString: |
location of a substring or NSNotFound |
substringFromIndex: / substringToIndex: / substringWithRange: |
parts of the string |
stringByAppendingString: / stringByAppendingFormat: |
a new, longer string |
stringByReplacingOccurrencesOfString:withString: |
search and replace |
componentsSeparatedByString: |
split into an NSArray |
uppercaseString / lowercaseString / capitalizedString |
case changes |
intValue / integerValue / doubleValue / boolValue |
number conversion |
Test yourself
How should you check whether two NSStrings contain the same text?
- a == b
- [a isEqualToString:b]
- [a compare:b] == YES
- strcmp(a, b)
What does [@"hello" rangeOfString:@"z"].location return?
- 0
- -1
- NSNotFound
- nil
What does [@"Hello" stringByAppendingString:@"!"] do to the original string?
- Changes it to Hello!
- Nothing: it returns a new string
- Raises an exception
- Appends to every copy