NSMutableString

From GNUstepWiki
Revision as of 20:43, 4 April 2007 by Kendall (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 = @"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 = @"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 = @"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 = @"a old string";
 [str replaceString: @"old" withString: @"new];
 // str is now = @"a new string"

This can also be done with ranges:

 NSMutableString *str = @"a old string";
 NSRange range = {2, 3};
 // start at index 2 and include the next 3 characters
 [str replaceCharactersInRange: range withString: @"new];
 // str is now = @"a new string"