Chapter 9. Manipulating Strings

In previous chapters, you learned how to store integer and floating-point numbers in a variable. However, one of the more common types of data to store is text, otherwise known as a string.

There are two parts to a string in Objective-C. First, you must identify a string by using the @ symbol, which identifies the string as a special Objective-C string. Second, you must enclose the string inside double quotation marks, such as @"This is a string" or @"555-1212 is also a string." Strings can contain any characters, including numbers, symbols, and letters.

To store and manipulate strings when creating Mac programs, you use a string class called NSString. One advantage of creating an object from an NSString class is that you can use all of the built-in methods for manipulating strings. In this chapter, you'll learn how to create string variables, how to manipulate strings using methods already created for you by the string class, and how to use two different kinds of string classes called NSString and NSMutableString. If you just need to store a string that will never change while your program runs, you can use the NSString class. If you need to modify a string while your program runs, you can use the NSMutableString class.

Declaring a String Variable

When you create a string variable (either an NSString or NSMutableString), you're working with objects, so you need to create a pointer such as the following:

NSString *myName;
NSMutableString *myOtherName;

To assign a string to an NSString variable, you simply use the equal sign like this:

NSString *myName;
myName = @"John Doe";

You can also declare a string and assign a value to it on one line:

NSString *myName = @"John Doe";

Once you assign a string to an NSString variable, you can never modify that string object again while your program runs. If you want to modify a string object while your program runs, you need to create an NSMutableString variable.

However, assigning a string to an NSMutableString variable is much different. Instead of directly assigning a string, you have to use the stringWithString method:

NSMutableString *myString;
myString = [NSMutableString stringWithString: @"This is a string"];

If you originally stored a string in an NSString object, you can't modify that string. However, you can modify a copy of that string by storing it in an NSMutableString object:

NSString *myName = @"John Doe";
NSMutableString *myString;
myString = [NSMutableString stringWithString: myName];

This code simply copies the string stored in the myName variable (NSString type) and stores it in myString (NSMutableString type). Once it is stored in myString, you can then manipulate the string by adding or deleting characters.

Getting the Length of a String

The length of a string includes the number of characters in the string plus any spaces in between. So the string @"Hello, world!" consists of 10 characters, 2 punctuation marks, and 1 space, for a total length of 13. To get the length of a string, you need to use the length method:

NSString *myName = @"John Doe";
int counter;
counter = [myName length];

To see how the length method works, follow these steps:

  1. Open the VariableTest project from the previous chapter.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSString *myString = @"Hello, world!";
        int counter;
        counter = [myString length];
        NSLog (@"String length = %i", counter);
    }
  4. Choose File

    Getting the Length of a String
  5. Click the Build and Run button or choose Build

    Getting the Length of a String
  6. Quit your program by clicking the Stop button or choosing Product

    Getting the Length of a String
  7. Choose Run

    Getting the Length of a String
    2010-09-04 17:15:49.929 VariableTest[29949:a0f] String length = 13

Comparing Two Strings

To check if two string pointers contain identical text, you have to use the isEqualToString method and list the two strings to compare:

[string1 isEqualToString: string2];

So if you wanted to compare the memory locations of two string pointers to determine whether they contain identical strings, you could use this code:

NSString *myName = @"John Doe";
NSString *hisName = @"John Doe";
if ([myName isEqualToString: hisName])
  {
   NSLog (@"The two strings are equal.");
  }

Checking for Prefixes and Suffixes

If you just want to check if a string begins or ends with a certain string such as "The" or a period, you can look for a specific prefix or suffix. To check for certain characters at the beginning of another string, use the hasPrefix method:

[string1 hasPrefix: string2];

Likewise, if you want to check if a string ends with certain characters, you can use the hasSuffix method:

[string1 hasSuffix: string2];

In both cases, the hasPrefix or hasSuffix method returns a YES or NO Boolean value. To see how these two methods work, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSString *myName = @"John Doe";
        NSString *hisName = @"John Doe";
        if ([myName isEqualToString: hisName])
        {
            NSLog (@"The two strings are equal using isEqualToString.");
        }
        BOOL flag;
        flag = [myName hasPrefix: @"John"];
    if (flag)
        {
            NSLog (@"The hasPrefix method returned YES.");
        }
    }
  4. Choose File

    Checking for Prefixes and Suffixes
  5. Click the Build and Run button or choose Build

    Checking for Prefixes and Suffixes
  6. Quit your program by clicking the Stop button or choosing Product

    Checking for Prefixes and Suffixes
  7. Choose Run

    Checking for Prefixes and Suffixes
    2010-09-04 19:43:03.883 VariableTest[30388:a0f] The two strings are equal using isEqualToString.
    2010-09-04 19:43:03.886 VariableTest[30388:a0f] The hasPrefix method returned YES.

Converting to Uppercase and Lowercase

You can modify the case of a string in three ways:

  • capitalizedString: Capitalizes the first letter of each word

  • lowercaseString: Converts every character to lowercase

  • uppercaseString: Converts every character to uppercase

Uppercase and lowercase only pertain to letters. Any other symbols such as numbers or punctuation marks won't be affected. To use these methods, you must assign the result to a string such as follows:

NSString *testString = @"Greetings from another planet.";
NSString *targetString;
targetString = [testString lowercaseString];

This would convert the testString text to lowercase and store the result in the targetString variable. To see how all these methods work for changing the case of a string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSString *testString = @"Greetings from another planet!";
        NSString *targetString;
        targetString = [testString uppercaseString];
    NSLog (@"All uppercase = %@", targetString);
        NSLog (@"**********");
        targetString = [testString lowercaseString];
        NSLog (@"All lowercase = %@", targetString);
        NSLog (@"**********");
        targetString = [testString capitalizedString];
        NSLog (@"All capitalized strings = %@", targetString);
        NSLog (@"**********");
        NSLog (@"Original string = %@", testString);
    }
  4. Choose File

    Converting to Uppercase and Lowercase
  5. Click the Build and Run button or choose Build

    Converting to Uppercase and Lowercase
  6. Quit your program by clicking the Stop button or choosing Product

    Converting to Uppercase and Lowercase
  7. Choose Run

    Converting to Uppercase and Lowercase
    2010-09-04 20:28:07.423 VariableTest[30522:a0f] All uppercase = GREETINGS FROM ANOTHER
    PLANET!
    2010-09-04 20:28:07.426 VariableTest[30522:a0f] **********
    2010-09-04 20:28:07.429 VariableTest[30522:a0f] All lowercase = greetings from another
    planet!
    2010-09-04 20:28:07.445 VariableTest[30522:a0f] **********
    2010-09-04 20:28:07.446 VariableTest[30522:a0f] All capitalized strings = Greetings From
    Another Planet!
    2010-09-04 20:28:07.447 VariableTest[30522:a0f] **********
    2010-09-04 20:28:07.454 VariableTest[30522:a0f] Original string = Greetings from another
    planet!

Notice that the original string never changes. These methods simply create a new result and store this new result in another string variable.

Converting Strings to Numbers

A string can hold a number, such as @"39.58" or @"43". If a string contains only a number (no letters or symbols), you can convert that string to a number data type such as an integer or a floating-point number using one of the following methods:

  • integerValue: Converts a string to an integer

  • floatValue: Converts a string to a floating-point value

  • doubleValue: Converts a string to a double value, which is a floating-point value that can retain more decimal places

To use one of these methods on a string that contains only a number (they won't work on strings that contain a mix of numbers and characters), use one of the three methods like this:

[stringName floatValue];

The preceding code would convert a string into an floating point value, which you could store into an floating point variable like this:

NSString *floatString = @"52.016";
    float myFloat;
    myFloat = [floatString floatValue];

You can also take a string, holding a floating-point value, and convert it into an integer by using the integerValue method. This cuts off the decimal portion of the number and retains only the integer value, such as turning @"39.78" into just 39.

You can also convert an integer string into a floating-point number using the floatValue method. This simply adds on zeros after the decimal point, such as turning @"58" into 58.000000.

To see these string-to-number conversion methods work, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSString *integerString = @"47";
        NSString *floatString = @"52.7016";
        int myInteger;
        float myFloat;
        myInteger = [integerString intValue];
        myFloat = [floatString floatValue];
        NSLog (@"Integer value = %i", myInteger);
        NSLog (@"Float value = %f", myFloat);
        NSLog (@"**********");
        myInteger = [floatString integerValue];
        myFloat = [integerString floatValue];
        NSLog (@"Integer value = %i", myInteger);
        NSLog (@"Float value = %f", myFloat);
    }
  4. Choose File

    Converting Strings to Numbers
  5. Click the Build and Run button or choose Build

    Converting Strings to Numbers
  6. Quit your program by clicking the Stop button or choosing Product

    Converting Strings to Numbers
  7. Choose Run

    Converting Strings to Numbers
    2010-09-05 09:22:07.334 VariableTest[31785:a0f] Integer value = 47
    2010-09-05 09:22:07.343 VariableTest[31785:a0f] Float value = 52.701599
    2010-09-05 09:22:07.345 VariableTest[31785:a0f] **********
    2010-09-05 09:22:07.347 VariableTest[31785:a0f] Integer value = 52
    2010-09-05 09:22:07.351 VariableTest[31785:a0f] Float value = 47.000000

Searching for a Substring

If you have a long string, you may need to know whether or not a certain word appears within that longer string. To determine that, you can search a string for a substring using the rangeOfString method.

To search for a substring within another string, you must declare a variable as an NSRange type:

NSRange myRange;

Then you must use the rangeOfString method to specify the substring to search for within the longer string:

[bigString rangeOfString: substring];

You next must assign the preceding code to the NSRange variable like this:

NSRange myRange;
myRange = [bigString rangeOfString: substring];

Note

NSRange is a structure, which is a special data structure that lets you store multiple variables (called fields) inside a single variable name. The complete NSRange structure looks like this:

typedef struct _NSRange {
      NSUInteger location;
      NSUInteger length;
} NSRange;

The location Field

The NSRange class includes two fields that you can use to store information about a string: location and length. The location field identifies where the substring appeared in the larger string. If the substring does not appear at all, then the location field contains a value of NSNotFound. If the substring does appear within the larger string, then the location field contains an integer value.

The length Field

If the location field contains an integer value, then the length field contains the length of the substring that was found.

To see how to search for a substring within a larger string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSRange myRange;
        NSString *bigString = @"Learning to program can be fun!";
        myRange = [bigString rangeOfString: @"can be"];
        if (myRange.location == NSNotFound)
        {
            NSLog (@"Substring is not in %@", bigString);
        }
        else
        {
            NSLog (@"Substring found at location = %i", myRange.location);
            NSLog (@"Substring length = %i", myRange.length);
        }
    }
  4. Choose File

    The length Field
  5. Click the Build and Run button or choose Build

    The length Field
  6. Quit your program by clicking the Stop button or choosing Product

    The length Field
  7. Choose Run

    The length Field
    2010-09-05 11:39:03.433 VariableTest[32079:a0f] Substring found at location = 20
    2010-09-05 11:39:03.436 VariableTest[32079:a0f] Substring length = 6

Searching and Replacing

In addition to searching for a substring within a larger string, you can also search for and replace parts of a string, using either of two techniques. First, you can replace part of a long string starting at a specific location. Second, you can search for a specific substring and replace it with a new substring.

To search for and replace part of a string with a new substring, use the NSMutableString class, which allows the string to change while your program runs.

Replacing Part of a String at a Specific Location

To replace a substring with another substring, you must specify the location and the length of the substring. The location, or index, defines where in the long string you want to start replacing characters.

When working with strings, the first character in a string is at index position 0, the second character is at index position 1, and so on, as shown in Figure 9-1.

A string is zero-based, so the first character is index 0, the second is index 1, and so on.

Figure 9-1. A string is zero-based, so the first character is index 0, the second is index 1, and so on.

To determine how many characters to replace, you have to specify a numeric value for the substring length. For example, suppose you had this string:

@"That is a large string."

If you wanted to replace the substring "is" in this string, you would have to specify an index of 5 and a length of 2.

Regardless of the original substring length, you can replace it with a new substring of a different length and the computer will adjust the longer string accordingly. So if you wanted to replace the word "is" with the phrase "was not", the longer string would now read "That was not a large string."

To replace part of a longer string with a substring, you need to use the following:

  • replaceCharactersInRange: Swaps out a specific location in a string with a substring

  • NSMakeRange(index, length): Defines the index in the string and the number of characters to replace

  • withString: Defines the new substring to insert into the longer string

Putting all of these together, you could use the following code:

[largeString replaceCharactersInRange: NSMakeRange(5,2) withString: @"was not"];

To see how to replace a substring in a specific location of a longer string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        [largeString replaceCharactersInRange: NSMakeRange(5,2) withString: @"was not"];
        NSLog (@"New string = %@", largeString);
    }
  4. Choose File

    A string is zero-based, so the first character is index 0, the second is index 1, and so on.
  5. Click the Build and Run button or choose Build

    A string is zero-based, so the first character is index 0, the second is index 1, and so on.
  6. Quit your program by clicking the Stop button or choosing Product

    A string is zero-based, so the first character is index 0, the second is index 1, and so on.
  7. Choose Run

    A string is zero-based, so the first character is index 0, the second is index 1, and so on.
    2010-09-05 17:29:04.890 VariableTest[32706:a0f] Original string = That is a string
    2010-09-05 17:29:04.893 VariableTest[32706:a0f] New string = That was not a string

Searching for and Replacing Part of a String

Suppose you want to search for and replace a substring within another string, but you do not know the exact location of the substring that you want to replace. As an alternative, you can search for a specific substring to replace regardless of its location in the longer string.

To search for and replace part of a longer string with a substring, you need to use the following:

  • replaceOccurrencesOfString: Defines a specific string to replace

  • withString: Defines the string to use and insert in a larger string

  • options: Defines different ways to search such as NSCaseInsensitiveSearch (ignores upper and lower case in a string), NSLiteralSearch (every character must exactly match), NSBackwardsSearch (starts searching from the end), NSAnchoredSearch (only searches from the beginning of the string, or the end if used with NSBackwardsSearch)

  • range: Defines the part of a larger string to search

Putting all of these together, you could use the following code:

[newString replaceOccurrencesOfString:@"another"
        withString:@"a modified"
        options:NSCaseInsensitiveSearch
        range:replaceRange];

This code would look in the newString variable for the substring "another" and replace it with the string "a modified".

To see how to search for and replace a substring in a longer string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *newString;
        newString = [NSMutableString stringWithString: @"This is another string."];
        NSLog (@"Original string = %@", newString);
        NSRange replaceRange = NSMakeRange(0, [newString length]);
        [newString replaceOccurrencesOfString:@"another"
            withString:@"a modified"
            options:NSCaseInsensitiveSearch
            range:replaceRange];
         NSLog (@"New string = %@", newString);
    }
  4. Choose File

    Searching for and Replacing Part of a String
  5. Click the Build and Run button or choose Build

    Searching for and Replacing Part of a String
  6. Quit your program by clicking the Stop button or choosing Product

    Searching for and Replacing Part of a String
  7. Choose Run

    Searching for and Replacing Part of a String
    2010-09-05 18:27:54.796 VariableTest[32799:a0f] Original string = This is another
    string.
    2010-09-05 18:27:54.799 VariableTest[32799:a0f] New string = This is a modified string.

Deleting Part of a String

Sometimes you may want to delete part of a string. To do this, you must delete a substring from an NSMutableString variable and use the following two methods:

  • deleteCharactersInRange: Deletes the substring defined by the rangeOfString method

  • rangeOfString: Defines the substring to delete

To use these methods on an NSMutableString, you could use code like this:

[largeString deleteCharactersInRange: [largeString rangeOfString: @"delete me"]];

This code would delete the string "delete me" from the string stored in the largeString variable. To see how to delete a substring from a longer string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        [largeString deleteCharactersInRange: [largeString rangeOfString: @"is a "]];
        NSLog (@"New string = %@", largeString);
    }
  4. Choose File

    Deleting Part of a String
  5. Click the Build and Run button or choose Build

    Deleting Part of a String
  6. Quit your program by clicking the Stop button or choosing Product

    Deleting Part of a String
  7. Choose Run

    Deleting Part of a String
    2010-09-05 18:56:28.351 VariableTest[32877:a0f] Original string = That is a string
    2010-09-05 18:56:28.354 VariableTest[32877:a0f] New string = That string

When deleting a substring from another string, you may also need to delete the space ahead or after the substring you're deleting. In the preceding example, notice that you must delete the string "is a" with a blank space after the letter a. If you simply deleted the string "is a", then there would be two spaces left to separate the remaining text, such as "That string", which may not be what you want.

Extracting a Substring

Deleting a substring just chops that substring out of a longer string and throws that substring away. In case you need to use that substring, you can yank it out and save it in a variable. There are two ways to extract a substring out of a longer string:

  • Specify the location in the longer string and the number of characters to extract

  • Specify the index in the longer string and yank out all characters starting from the defined location to the end of the string

The first method lets you yank out substrings from the middle of a longer string, such as yanking out the word "you" from the longer string "Hello all you people."

The second method can extract a substring only from a specific index to the end of the string, making it impossible to extract just a middle portion of a string.

Extracting a Substring with a Location and Length

To extract a substring from a longer string, you need to use the following:

  • substringWithRange: Extracts a substring defined by NSMakeRange

  • NSMakeRange(index, length): Defines the index and number of characters to extract

When you extract a substring, you're copying part of the original string, so you can extract a substring from either an NSString or NSMutableString like this:

[largeString substringWithRange: NSMakeRange(X,Y)];

The preceding code returns a string that you can assign to an NSString variable like this:

NSString *myString;
myString = [largeString substringWithRange: NSMakeRange(X,Y)];

To see how to extract a substring and how it can affect your original string, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        NSString *newString;
        newString = [largeString substringWithRange: NSMakeRange(5, 4)];
        NSLog (@"New string = %@", newString);
    }
  4. Choose File

    Extracting a Substring with a Location and Length
  5. Click the Build and Run button or choose Build

    Extracting a Substring with a Location and Length
  6. Quit your program by clicking the Stop button or choosing Product

    Extracting a Substring with a Location and Length
  7. Choose Run

    Extracting a Substring with a Location and Length
    2010-09-05 20:09:00.058 VariableTest[33337:a0f] Original string = That is a string
    2010-09-05 20:09:00.063 VariableTest[33337:a0f] New string = is a

Extracting a Substring to the End of a String

A much simpler, but limited, way to extract a substring out of a longer string is to specify a location in the longer string using the substringFromIndex method, which looks like this:

[largeString substringFromIndex: X];

The preceding code returns a string where the value of X is the index of the first character that you want in your substring. Whatever location you choose (any value, starting with 0), the substringFromIndex method yanks out that substring from that location to the end of the string.

To see how the substringFromIndex method works, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        NSString *newString;
        newString = [largeString substringFromIndex: 5];
        NSLog (@"New string = %@", newString);
    }
  4. Choose File

    Extracting a Substring to the End of a String
  5. Click the Build and Run button or choose Build

    Extracting a Substring to the End of a String
  6. Quit your program by clicking the Stop button or choosing Product

    Extracting a Substring to the End of a String
  7. Choose Run

    Extracting a Substring to the End of a String
    2010-09-05 20:20:13.495 VariableTest[33385:a0f] Original string = That is a string
    2010-09-05 20:20:13.500 VariableTest[33385:a0f] New string = is a string

Appending a Substring

If you have defined a string as an NSMutableString, you can append text to the end of it by using the appendString method like this:

[largeString appendString: @" Newly added string"];

Whatever text the largeString variable contains, it now includes the string "Newly added string" at the end. When appending text to a string, you may need to put a space ahead of the appended text so that the newly added string doesn't get smashed together with the other string.

To see how to use the appendString method, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        [largeString appendString: @" and this is a string too."];
        NSLog (@"New string = %@", largeString);
    }
  4. Choose File

    Appending a Substring
  5. Click the Build and Run button or choose Build

    Appending a Substring
  6. Quit your program by clicking the Stop button or choosing Product

    Appending a Substring
  7. Choose Run

    Appending a Substring
    2010-09-05 20:30:33.054 VariableTest[33424:a0f] Original string = That is a string
    2010-09-05 20:30:33.059 VariableTest[33424:a0f] New string = That is a string and this is a string too.

Inserting a String

The appendString method adds a new string to the end of an existing one. If you want to add text in the middle or at the beginning of a string, you have to use the insertString method and specify the index with the atIndex method like this:

[largeString insertString: @" Newly added string" atIndex: X];

The insertString method defines the string to add, and the atIndex method defines the location in which to insert the string inside another string. When inserting a string inside an existing one, you may need to add an extra space before or after the inserted string so that the text does not appear smashed together.

To see how the insertString method works, follow these steps:

  1. Open the VariableTest project from the previous section.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSMutableString *largeString;
        largeString = [NSMutableString stringWithString: @"That is a string"];
        NSLog (@"Original string = %@", largeString);
        [largeString insertString: @"was and still " atIndex: 5];
        NSLog (@"New string = %@", largeString);
    }
  4. Choose File

    Inserting a String
  5. Click the Build and Run button or choose Build

    Inserting a String
  6. Quit your program by clicking the Stop button or choosing Product

    Inserting a String
  7. Choose Run

    Inserting a String
    2010-09-05 20:37:54.657 VariableTest[33470:a0f] Original string = That is a string
    2010-09-05 20:37:54.661 VariableTest[33470:a0f] New string = That was and still is a
    string

Summary

After numbers, strings are the second most common type of data for programs to store and manipulate. If you just need to store a string and never modify it, you can declare an NSString variable. If you need to modify a string while your program runs, then you must declare an NSMutableString variable.

The way in which you assign a value to a string variable differs depending on whether you're using an NSString or NSMutableString. With an NSString, you can simply assign a value with the equal sign like this:

NSString *myString;
myString = @"My new string contents";

To assign a string to an NSMutableString variable, you must use the stringWithString method like this:

NSMutableString *myString;
myString = [NSMutableString stringWithString: @"My new string contents"];

Strings are any character inside double quotation marks and preceded by a @ symbol. If you store numbers as a string, you can convert those strings into actual integer or floating-point values.

When modifying strings, keep in mind that you may need empty spaces to prevent text from smashing together. Also when manipulating strings, you may need to specify an index position of a string. The first character of a string is considered to be at index 0, the second is at index 1, and so on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.55.43