Objective C Tutorial - Objective C Strings






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;
}




Methods

The following lists some useful methods for working with Strings.

  • - (NSString *)capitalizedString;
    capitalize the string.
  • - (unichar)characterAtIndex:(NSUInteger)index;
    get the character at a given index.
  • - (double)doubleValue;
    Converts string value to the double value.
  • - (float)floatValue;
    Converts to float value.
  • - (BOOL)hasPrefix:(NSString *)aString;
    Checks if the string is started with another string.
  • - (BOOL)hasSuffix:(NSString *)aString;
    Checks if the string is ended with another string.
  • - (id)initWithFormat:(NSString *)format ...;
    Formats a string.
  • - (NSInteger)integerValue;
    Converts string to NSInteger value.
  • - (BOOL)isEqualToString:(NSString *)aString;
    Compares two strings.
  • - (NSUInteger)length;
    Returns the number of characters in the String.
  • - (NSString *)lowercaseString;
    Lowercase the String.
  • - (NSRange)rangeOfString:(NSString *)aString;
    Searches a sub string.
  • - (NSString *)stringByAppendingFormat:(NSString *)format ...;
    Appends to string with format.
  • - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
    Trims characters from the string.
  • - (NSString *)substringFromIndex:(NSUInteger)anIndex ;
    Gets the sub string from index.




Example

#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;
}

Using Strings

#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;
}