The string in Objective-C is represented using NSString or NSMutableString.
NSString is for a immutable string while NSMutableString is for a mutable string. NSMutableString is a subclass of NSString.
The simplest way to create a string is to use the Objective-C @"..."
construct.
NSString *greeting = @"Hello";
A simple example for creating and printing a string is shown below.
#import <Foundation/Foundation.h> int main () { NSString *greeting = @"Hello"; NSLog(@"Greeting message: %@\n", greeting ); return 0; }
The following lists some useful methods for working with Strings.
#import <Foundation/Foundation.h> int main () { NSString *str1 = @"Hello"; NSString *str2 = @"World"; NSString *str3; int len ; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; str3 = [str2 uppercaseString]; NSLog(@"Uppercase String : %@\n", str3 ); str3 = [str1 stringByAppendingFormat:@"World"]; NSLog(@"Concatenated string: %@\n", str3 ); len = [str3 length]; NSLog(@"Length of Str3 : %d\n", len ); str3 = [[NSString alloc] initWithFormat:@"%@ %@",str1,str2]; NSLog(@"Using initWithFormat: %@\n", str3 ); [pool drain]; return 0; }
#import <Foundation/Foundation.h> int main () { NSString *myName; myName = @"John Smith"; int counter; int myAge = 49; float myPaycheck = 5120.75; for (counter = 0; counter < 3; counter++) { NSLog (@"This is my age: %i", myAge); NSLog (@"This is my paycheck amount: %f", myPaycheck); } NSLog (@"This is my name: %@", myName); return 0; }