NSMutableString

From GNUstepWiki
Revision as of 04:50, 12 May 2009 by Newacct (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

NSMutableString inherits from NSString, but includes methods for changing the string.

Editing Strings

Adding To Strings

Strings can be added on to by appending the new substring to the end, or by inserting it any where in the middle.

Appending Strings

The simplest way to edit a string is by appending to the end of the string, as shown here:

 NSMutableString *str = [NSMutableString stringWithString: @"short string"];
 [str appendString: @" made longer"];
 // str is now = @"short string made longer"

C style formating flags can also be used as follows:

 NSMutableString *str = [NSMutableString stringWithString: @"short string"];
 [str appendFormat: @" made longer %@.", @"with formating"];
 // str is now = @"short string made longer with formating."

Inserting Substrings

The more advanced method of adding to strings in by insertion, as demonstrated here:

 NSMutableString *str = [NSMutableString stringWithString: @"a string"];
 [str insertString: @"new " atIndex: 2];
 // str is now = @"a new string"

Replacing Substrings

A certain substring can be replaced with a new one as follows:

 NSMutableString *str = [NSMutableString stringWithString: @"a old string"];
 [str replaceString: @"old" withString: @"new];
 // str is now = @"a new string"

This can also be done with ranges:

 NSMutableString *str = [NSMutableString stringWithString: @"a old string"];
 // start at index 2 and include the next 3 characters
 [str replaceCharactersInRange: NSMakeRange(2, 3) withString: @"new];
 // str is now = @"a new string"