Error:

Create NSString from another NSString

NSString *s = [NSString stringWithString:anotherString];

Create NSString from ASCII C String

// const char *bytes = ...
NSString *s = [NSString stringWithCString:bytes encoding:NSASCIIStringEncoding];

Create NSString from UTF8 C String

// const char * bytes = ...
NSString *s = [NSString stringWithUTF8String:bytes];

Create NSString from NSData

// replace NSUTF8StringEncoding with required encoding
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Create NSString from format

NSString *s = [NSString stringWithFormat:@"%d %f", intVar, floatVar];

Read file to string

NSError *err = nil;
NSString *s = [NSString stringWithContentsOfFile:@"/path/to/file-utf8.txt" encoding:NSUTF8StringEncoding error:&err];
if (s == nil)
    NSLog(@"Error reading file: %@", err.localizedDescription);

Read URL to string

NSError *err = nil;
NSURL *url = [NSURL fileURLWithPath:@"/path/to/file-utf8.txt"];
NSString *s = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&err];
if (s == nil)
    NSLog(@"Error reading file: %@", err.localizedDescription);

Save string to URL

NSError *err = nil;
NSString *str = @"string";
NSURL *url = [NSURL fileURLWithPath:@"/path/to/file-utf8.txt"];
if (![str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err])
    NSLog(@"Error reading file: %@", err.localizedDescription);

Save string to file

NSError *err = nil;
NSString *str = @"string";
if (![str writeToFile:@"/path/to/file-utf8.txt" atomically:YES encoding:NSUTF8StringEncoding error:&err])
    NSLog(@"Error reading file: %@", err.localizedDescription);

Get length of the string

NSString *s = @"test";
// len is 4
NSUInteger len = [s length];

Get string representation length for given encoding

NSString *s = @"Straße";
// len is 7
NSUInteger len = [s lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

Get character at index

NSString *s = @"Straße";
// ch is 223
unichar ch = [s characterAtIndex:4];
NSLog(@"%d", ch);

Get characters of the string in given range

NSString *s = @"Straße";
unichar subs[2];
// subs is {223, 101}
[s getCharacters:subs range:NSMakeRange(4, 2)];

Convert NSString to C string (new buffer)

const char *cstr = [s cStringUsingEncoding:NSASCIIStringEncoding];

Convert NSString to C string (provide buffer)

char *buffer[BUFFER_SIZE];
[s getCString:buffer maxLength:BUFFER_SIZE encoding:NSASCIIStringEncoding];

Convert NSString to UTF-8 C string

const char *cstr = [s UTF8String];

Append formatted string to NSString

NSString *newStr = [s stringByAppendingFormat:@"%d %f", intVar, floatVar];

Append NSString string to NSString

NSString *newStr = [s stringByAppendingString:@" append this"];

Pad NSString with another string or character

// Results is "abc......"
[@"abc" stringByPaddingToLength:9 withString:@"." startingAtIndex:0];
    

Get first N characters of the string

// Result is @"123"
NSString *s = [@"123456" substringToIndex:3];

Get last N characters of the string

// Result is @"456"
NSString *s = [@"123456" substringFromIndex:3];

Get substring of NSString

// Result is "34"
NSString *s = [@"12345" substringWithRange:NSMakeRange(2,2)];

Trim characters from both ends of NSString

// Result is "long_string"
NSString *s = [@"__long_string__" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"_"]];

Trim whitespaces from both ends of NSString

// Result is "long string"
NSString *s = [@"  long string  " stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Trim newline characters from both ends of NSString

// Result is "long string"
NSString *s = [@"long string\n\n\n" stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Split NSString using string

// Result: ("One", "two", "three")
NSArray *a = [@"One, two, three" componentsSeparatedByString:@", "];

Split NSString using set of characters

//  Result: ("", "One", "two", "", "three,", "")
NSArray *a = [@" One\ttwo\t\tthree " componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Find location of first instance of character in the string

// Result is: range.location = 3, range.length = 1
NSRange range = [@"One Two Three" rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];

Find location of last instance of character in the string

// Result is: range.location = 7, range.length = 1
NSRange range = [@"One Two Three" rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet] options:NSBackwardsSearch];

Find location of first instance of substring in the string

// Result is: range.location = 4, range.length = 3
NSRange range = [@"One Two Three Two" rangeOfString:@"Two"];

Find location of last instance of substring in the string

// Result is: range.location = 14, range.length = 3
NSRange range = [@"One Two Three Two" rangeOfString:@"Two" options:NSBackwardsSearch];

Enumerate all lines in NSString using block

// Output is:
// --> One
// --> Two
// --> Three
// -->
[@"One\nTwo\nThree\n\n" enumerateLinesUsingBlock:^(NSString* line, BOOL *stop)
 {
     NSLog(@"--> %@", line);
 }];

Enumerate all paragraphs in NSString using block

[s enumerateSubstringsInRange:NSMakeRange(0, s.length)
                      options:NSStringEnumerationByParagraphs
                   usingBlock:^(NSString* line, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
 {
     NSLog(@"--> %@", line);
 }];

Enumerate all words in NSString using block

[s enumerateSubstringsInRange:NSMakeRange(0, s.length)
                      options:NSStringEnumerationByWords
                   usingBlock:^(NSString* line, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
 {
     NSLog(@"--> %@", line);
 }];

Enumerate all sentences in NSString using block

[s enumerateSubstringsInRange:NSMakeRange(0, s.length)
                      options:NSStringEnumerationBySentences
                   usingBlock:^(NSString* line, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
 {
     NSLog(@"--> %@", line);
 }];

Replace all occurrences of string in NSString (case sensitive)

// Result is: "One 2 three"
[@"One Two Three" stringByReplacingOccurrencesOfString:@"Two" withString:@"2"];

Replace all occurrences of string in NSString (case insensitive)

// Result is: "One 2 three"
NSString *s = @"One Two Three";
[s stringByReplacingOccurrencesOfString:@"two" withString:@"2" options:NSCaseInsensitiveSearch range:NSMakeRange(0, s.length)];

Replace portion of the string with another string

// Result is: "1 Two Three"
[@"One Two Three" stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:@"1"];

Parse property list

// obj is NSDictionary
id obj = [@"{ key = value; }" propertyList];

Parse content of strings file

NSDictionary *dict = [@"\"One\" = \"Uno\";" propertyListFromStringsFileFormat];

Get strings order

// r is either NSOrderedAscending, NSOrderedDescending or NSOrderedSame
NSComparisonResult r = [s compare:anotherString];

Get strings order (localized)

// r is either NSOrderedAscending, NSOrderedDescending or NSOrderedSame
NSComparisonResult r = [s localizedCompare:anotherString];

Get strings order (case-insensitive)

// r is either NSOrderedAscending, NSOrderedDescending or NSOrderedSame
NSComparisonResult r = [s caseInsensitiveCompare:anotherString];

Get strings order (localized, case-insensitive)

// r is either NSOrderedAscending, NSOrderedDescending or NSOrderedSame
NSComparisonResult r = [s localizedCaseInsensitiveCompare:anotherString];

Check if the string is equal to another string

BOOL equal = [s isEqualToString:anotherString];

Check if the string begins with another string

// Result is YES
BOOL begins = [@"One Two" hasPrefix:@"One"];

Check if the string ends with another string

// Result is YES
BOOL begins = [@"One Two" hasSuffix:@"Two"];

Hash value for NSString

NSUInteger hashVal = [@"One Two" hash];

Common prefix for two strings

// Result is "One "
[@"One Two Three" commonPrefixWithString:@"One more bit" options:NSLiteralSearch];

Capitalize words in the string

// Result is "One Two Three"
NSString *s = [@"one two three" capitalizedString];

Uppercase the string

// Result is "ONE TWO THREE"
NSString *s = [@"one two three" uppercaseString];

Lowercase the string

// Result is "one two three"
NSString *s = [@"One Two Three" lowercaseString];

Convert NSString to float

float f = [@"0.15" floatValue];

Convert NSString to double

double d = [@"0.15" doubleValue];

Convert NSString to int

int i = [@"15" intValue];

Convert NSString to integer

NSInteger i = [@"15" integerValue];

Convert NSString to long long

long long i = [@"15" longLongValue];

Convert NSString to bool

// Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1
// Result is YES
BOOL b = [@"yes" boolValue];

List of available string encodnigs

// zero-terminated list
const NSStringEncoding *encodings = [NSString availableStringEncodings];

Default C string encoding

NSStringEncoding e = [NSString defaultCStringEncoding];

Get localized name of encoding

// Result is "Western (ISO Latin 1)"
NSString *name = [NSString localizedNameOfStringEncoding:NSISOLatin1StringEncoding];

Check if the string can be converted to encoding

// Result is NO
BOOL ok = [@"Straße" canBeConvertedToEncoding:NSWindowsCP1251StringEncoding];

Convert NSString to given encoding (lossy)

// Result is "Stra?e"
NSData *bytes = [@"Straße" dataUsingEncoding:NSWindowsCP1251StringEncoding allowLossyConversion:YES]

Convert NSString to given encoding

// Result is "Stra\xdfe"
NSData *bytes = [@"Straße" dataUsingEncoding:NSISOLatin1StringEncoding];

Create absolute path with components

[NSString pathWithComponents:[NSArray arrayWithObjects:@"/", @"one", @"two", @"three", nil]]

Create path with components

// Result is "one/two/three"
NSString *s = 
[NSString pathWithComponents:[NSArray arrayWithObjects:@"one", @"two", @"three", nil]];

Get path components

NSArray *components = [@"/one/two/three" pathComponents];

File system-specific representation of the path

const char *s = [@"/one/two/three" fileSystemRepresentation];

Check if the path is absolute

// Result is YES
BOOL absolute = [@"/one/two/three" isAbsolutePath];

Get last path component

// Result is "three.txt"
NSString *file = [@"/one/two/three.txt" lastPathComponent];

Get file extension

// Result is "txt"
NSString *ext = [@"/one/two/three.txt" pathExtension];

Abbreviate the path using tilde

// Result is "~/x.txt
NSString *path = [@"/Users/gonzo/x.txt" stringByAbbreviatingWithTildeInPath];

Add path component

// Result is "/one/two/three.txt"
NSString *path = [@"/one/two" stringByAppendingPathComponent:@"three.txt"];

Add file extension to the path

// Result is "/one/two/three.txt"
NSString *path = [@"/one/two/three" stringByAppendingPathExtension:@"txt"];

Get directory part of the path

// Result is "/one/two"
NSString *path = [@"/one/two/three.txt" stringByDeletingLastPathComponent];

Remove file extension from the path

// Result is "/one/two/three"
NSString *path = [@"/one/two/three.txt" stringByDeletingPathExtension];

Change extension in the path

// Result is "/one/two/three.rtf"
NSString *path = [[@"/one/two/three.txt" stringByDeletingPathExtension] stringByAppendingPathExtension:@"rtf"];

Expand tilde in the path

// Result is "/Users/user/x.txt"
NSString *path = [@"~user/x.txt" stringByExpandingTildeInPath];

Resolve symlinks in the path

NSString *resolved = [path stringByResolvingSymlinksInPath];

Standartize path

// Result is "/Users/user/foo"
NSString *std = [@"~/bar/..//.//foo" stringByStandardizingPath];

URL-encode string by percent-escaping characters

// Result is "Stra%DFe"
NSString *escaped = [@"Straße" stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];

Convert URL-encoded string to normal form

// Result is "Straße"
NSString *str = [@"Stra%DFe" stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];

Convert URL-encoded string to normal form (UTF-8)

// Result is "Straße"
NSString *str = [@"Stra%C3%9Fe" stringByRemovingPercentEncoding];

Create mutable copy of the string

NSMutableString *mutable = [string mutableCopy];