2012年5月25日 星期五

Mutable Strings Operation

refer to Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)

int main (int argc, char *argv[])
{
NSAutoreleasePool  * pool = [[NSAutoreleasePool alloc] init];
NSString  *str1 = @ ” This is string A ” ;
NSString  *search, *replace;
NSMutableString  *mstr;
NSRange   substr;

// Create immutable string from nonmutable
mstr = [NSMutableString  stringWithString: str1];
NSLog (@ ” %@ ” , mstr);

// Insert characters
[mstr insertString: @ ” mutable ” atIndex: 7];
NSLog (@ ” %@ ” , mstr);

// Effective concatentation if insert at end
[mstr insertString: @ ” and string B ” atIndex: [mstr length]];
NSLog (@ ” %@ ” , mstr);

//  Or can use appendString directly
[mstr appendString: @ ” and string C ” ];
NSLog (@ ” %@ ” , mstr);

// Delete substring based on range
[mstr deleteCharactersInRange: NSMakeRange (16, 13)];
NSLog (@ ” %@ ” , mstr);

// Find range first and then use it for deletion
substr = [mstr  rangeOfString: @ ” string B and  “ ];

if (substr.location != NSNotFound) {
    [mstr deleteCharactersInRange: substr];
    NSLog (@ ” %@ ” , mstr);
}

// Set the mutable string directly
[mstr setString: @ ” This is string A ” ];
NSLog (@ ” %@ ” , mstr);

// Now let ’ s replace a range of chars with another
[mstr replaceCharactersInRange: NSMakeRange(8, 8) withString: @ ” a mutable string ” ];
NSLog (@ ” %@ ” , mstr);

// Search and replace
search = @ ” This is ” ;
replace = @ ” An example of ” ;
substr = [mstr  rangeOfString: search];
if (substr.location != NSNotFound) { // 把" This is "換成"An example of "
   [mstr replaceCharactersInRange: substr withString: replace]; 
   NSLog (@ ” %@ ” , mstr);
}

// Search and replace all occurrences
search = @ ” a ” ;
replace = @ ” X ” ;
substr = [mstr rangeOfString: search];
while (substr.location != NSNotFound) {  //把a換成X
   [mstr replaceCharactersInRange: substr   withString: replace];
   substr = [mstr rangeOfString: search];
}
NSLog (@ ” %@ ” , mstr);

[pool drain];
return 0;
}
This is string A
This is mutable string A
This is mutable string A and string B
This is mutable string A and string B and string C
This is mutable string B and string C
This is mutable string C
This is string A
This is a mutable string
An example of a mutable string
An exXmple of X mutXble string

沒有留言: