Manipulating Mutable String Objects

You can choose from a variety of String Services functions to add to and modify the contents of mutable CFString objects. These functions, as one might expect, do not work on immutable CFString objects. If you want to change the contents of a CFString object, you must either start with a content-less mutable CFString object or make a mutable copy of an immutable CFString object. See Creating Mutable String Objects for information on creating objects of this kind.

The functions that manipulate mutable CFString objects fall into several categories:

Listing 12 exemplifies several of the functions that manipulate mutable CFString objects:

Listing 12 Various operations on a mutable string
void mutableStringOperations() { CFMutableStringRef mstr; CFRange range; StringPtr pbuf; CFIndex length; mstr = CFStringCreateMutable(NULL, 0); CFStringAppend(mstr, CFSTR("Now is the time for all good men to come to the aid of their ")); CFStringAppend(mstr, CFSTR("party.")); CFShow(CFSTR("Mutable String 1 - Appended CFStrings")); CFShow(mstr); range = CFStringFind(mstr, CFSTR("good"), 0); if (range.length > 0) { CFStringReplace(mstr, range, CFSTR("bad")); CFShow(CFSTR("Mutable String 2 - Replaced substring")); CFShow(mstr); } CFStringAppendPascalString(mstr, "\p Now is the time for a party.", CFStringGetSystemEncoding()); CFStringDelete(mstr, CFRangeMake(10, 20)); CFShow(CFSTR("Mutable String 3 - Pascal string added, characters in middle deleted:")); CFShow(mstr); CFStringUppercase(mstr, NULL); CFShow(CFSTR("Mutable String 4 - Convert to uppercase:")); CFShow(mstr); }

When compiled and run, this code generates the following output:

 Mutable String 1 - Appended CFStrings 
 Now is the time for all good men to come to the aid of their party. 
 Mutable String 2 - Replaced substring 
 Now is the time for all bad men to come to the aid of their party. 
 Mutable String 3 - Pascal string added, characters in middle deleted: 
 Now is then to come to the aid of their party. Now is the time for a party. 
 Mutable String 4 - Convert to uppercase: 
 NOW IS THEN TO COME TO THE AID OF THEIR PARTY. NOW IS THE TIME FOR A PARTY. 

© 1999 Apple Computer, Inc. – (Last Updated 07 September 99)