Previously we learn how to create Array in Objective C: Objective-C : Arrays


The string in Objective-C programming language is represented using NSString and its subclass NSMutableString provides several ways for creating string objects. The simplest way to create a string object is to use the Objective-C @"..." construct:

NSString *greeting = @"Hello";

Strings without NSString

Objective-C is built upon the C programming language. C also has a mechanism for dealing with strings, but because C is not an object oriented programming language it does not have any of the advantages offered to us through the NSString class. For example, to use the C approach to creating strings we have to set up a pointer to a string of characters:

char *myString = "This is a C character string";

Alternatively, we could define a C style character array to contain a string:

char myString[] = "This is a C character array";

Having created the string we literally have nothing but a section of memory where a null terminated string of characters is located. If we want to do anything to manipulate the string we will have to write our own code to do it.


By using NSString, however, we get access to a wide range of methods provided with that class to manipulate our string without having to write all the code ourselves.

In addition, C style character strings are composed of single byte characters and therefore limited in the range of characters that can be stored. This usually becomes a problem when dealing with non-ASCII character sets used by foreign languages. NSString objects, on the other hand, are comprised of multibyte Unicode characters and can handle just about any language character set.


The NSString class declares the programmatic interface for an object that manages immutable strings. An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString is implemented to represent an array of Unicode characters, in other words, a text string.


The mutable subclass of NSString is NSMutableString.

[The NSMutableString class declares the programmatic interface to an object that manages a mutable string—that is, a string whose contents can be edited—that conceptually represents an array of Unicode characters. To construct and manage an immutable string—or a string that cannot be changed after it has been created—use an object of the NSString class.]


The NSString class has two primitive methods—length and characterAtIndex: —that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0. 

NSString declares methods for finding and comparing strings. It also declares methods for reading numeric values from strings, for combining strings in various ways, and for converting a string to different forms (such as encoding and case changes).


Declaring Constant String Objects

A constant string object is declared by encapsulating the string in double quotes (") preceded by an @ sign. For example:

@"This is a constant character string object";

In order to display the current value of a string object using NSLog, simply reference the string using '%@' as follows:

NSLog (@"%@", @"This is a constant character string object");

Even though all we are doing here is creating a constant string object, keep in mind that this is still an object. As such, it has a range of methods that we can call on it. For example string objects have a length method that returns the number of characters in the string. We can, therefore, call this on a constant string object:

int len = [@"Hello" length];
NSLog (@"Length of string = %i", len);

The above code declares a constant string object containing the word "Hello" and calls the length method of object. The result is assigned to an integer variable named len which in turn is displayed using NSLog. When compiled and executed, we get the following output:

Length of string = 5

Constant string objects are actually instantiated from the NSConstantString class which, much like the other classes we will look at in this chapter, is actually a subclass of the NSString class. In practice, given the way that constant strings are used, it is unlikely that you will need to specifically declare your string constants as being of type NSConstantString. It is more likely that you will declare the string as we have done in this section and let the compiler handle the rest.


Creating Mutable and Immutable String Objects

Two additional types of Objective-C string objects are mutable and immutable. When you create a string object of type NSString you are creating an immutable string object. This means that once a string has been assigned to the object, that string cannot subsequently be modified in any way.

NSString *string1 = @"This string is immutable";

Mutable string objects, on the other hand, are declared using the NSMutableString class and allow the string contained within the object to be modified using a variety of methods (some of which will be covered in the remainder of this chapter). NSMutableString is a subclass of NSString, which in turn is a subclass of NSObject. Mutable strings cannot be initialized simply by assigning a constant string object as we did above since that will just give us a pointer to an immutable constant string object. Instead, the string constant must be copied into the mutable string object. For example:

NSMutableString *string2 = [NSMutableString stringWithString:@"This string is

Once a string has been declared as immutable, the only way to get a mutable version of the string is to create a mutable string object and copy the contents of the immutable string object to it. This can be achieved using the NSMutableString stringWithString class method. For example:

NSString *string1 = @"This is a string";
NSMutableString *string2;
string2 = [NSMutableString stringWithString: string1];

Once executed, the above code will create an immutable string object (string1) initialized with the text "This is a string" and an empty pointer to an immutable string object (string2). The stringWithString class method of the NSMutableString class is then called, passing though the immutable string1 as an argument. This method returns a new object containing the immutable string and assigns it to string2. We now have a mutable copy of the immutable string1 object.


Objective-C supports a wide range of methods for manipulate strings:

Method & Purpose


- (NSString *)capitalizedString;

Returns a capitalized representation of the receiver.


- (unichar)characterAtIndex:(NSUInteger)index;

Returns the character at a given array position.


- (double)doubleValue;

Returns the floating-point value of the receiver’s text as a double.


- (float)floatValue;

Returns the floating-point value of the receiver’s text as a float.


- (BOOL)hasPrefix:(NSString *)aString;

Returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.


- (BOOL)hasSuffix:(NSString *)aString;

Returns a Boolean value that indicates whether a given string matches the ending characters of the receiver.


- (id)initWithFormat:(NSString *)format ...;

Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted.


- (NSInteger)integerValue;

Returns the NSInteger value of the receiver’s text.


- (BOOL)isEqualToString:(NSString *)aString;

Returns a Boolean value that indicates whether a given string is equal to the receiver using a literal Unicode-based comparison.


- (NSUInteger)length;

Returns the number of Unicode characters in the receiver.


- (NSString *)lowercaseString;

Returns lowercased representation of the receiver.


- (NSRange)rangeOfString:(NSString *)aString;

Finds and returns the range of the first occurrence of a given string within the receiver.


- (NSString *)stringByAppendingFormat:(NSString *)format ...;

Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.


- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;

Returns a new string made by removing from both ends of the receiver characters contained in a given character set.


- (NSString *)substringFromIndex:(NSUInteger)anIndex;

Returns a new string containing the characters of the receiver from the one at a given index to the end.


Following example makes use of few of the above-mentioned functions:

#import <Foundation/Foundation.h>
int main ()
   NSString *str1 = @"Hello";
   NSString *str2 = @"World";
   NSString *str3;
   int  len ;

   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   /* uppercase string */
   str3 = [str2 uppercaseString];
   NSLog(@"Uppercase String :  %@\n", str3 );

   /* concatenates str1 and str2 */
   str3 = [str1 stringByAppendingFormat:@"World"];
   NSLog(@"Concatenated string:   %@\n", str3 );

   /* total length of str3 after concatenation */
   len = [str3 length];
   NSLog(@"Length of Str3 :  %d\n", len );
   /* InitWithFormat */
    str3 = [[NSString alloc] initWithFormat:@"%@ %@",str1,str2]; 
    NSLog(@"Using initWithFormat:   %@\n", str3 );
    [pool drain];
   return 0;

When the above code is compiled and executed, it produces result something as follows:

2015-07-10 06:24:44.747 demo[15557] Uppercase String : WORLD
2015-07-10 06:24:44.748 demo[15557] Concatenated string: HelloWorld
2015-07-10 06:24:44.748 demo[15557] Length of Str3 : 10
2015-07-10 06:24:44.748 demo[15557] Using initWithFormat: Hello World


Next, we will learn about: Objective-C : NSDictionary  class

  Modified On Nov-29-2017 10:50:44 PM

Leave Comment