NSString Tutorial

String Creation

The most common way to work with NSString in Objective-C is to use the literal syntax @"I'm a string


NSString *firstName = @"Jack";
NSString *lastName = @"Smith";
int age = 25;
NSString *display = [NSString stringWithFormat: @"My name is %@ and I am %d years old!", firstName, age];
NSLog(@"%@", display);

NSString *firstName = @"Jack";
NSString *lastName = @"Smith";
int age = 25;
NSString *display = [NSString stringWithFormat: @"My name is %@ and I am %d years old!", firstName, age];
NSLog(@"%@", display);

String Comparison


NSString *vehicle = @"R8";
NSString *vehicle2 = @"Bronco II";

if ([vehicle isEqualToString: @"R8"]) {
  NSLog(@"You drive a cool car!");
}

if ([vehicle hasPrefix: @"Bronco"]) {
  NSLog(@"You have some type of Bronco");
}

if ([vehicle hasSuffix: @"II"]) {
  NSLog(@"You are driving a Bronco II");
}

if ([vehicle caseInsensitiveCompare: vehicle2] == NSOrderedSame) {
  NSLog(@"They are the same");
}

String Enumeration


NSString *car = @"BMW";
for (int a=0; a < [car length];  ++) {
    unichar letter = [car characterAtIndex:a];
    NSLog(@"%d: %hu", a, letter);
}

String Modification


NSString *firstName = @"John";
NSString *allocatedString = [[NSString alloc]init];

NSLog(@"Name: %@", firstName);

NSString *fullName = [NSString stringWithFormat:@"%@ Smith %@", firstName, @"Charles the III"];

NSString *display = [fullName stringByAppendingString:@" - Died 1448"];

NSLog(@"Fullname: %@", fullName);