Difference between revisions of "NSMutableString"

From GNUstepWiki
Jump to navigation Jump to search
 
m
Line 44: Line 44:
 
   [str replaceCharactersInRange: range withString: @"new];
 
   [str replaceCharactersInRange: range withString: @"new];
 
   // str is now = @"a new string"
 
   // str is now = @"a new string"
 +
 +
 +
[[Category:Foundation]]
 +
[[Category:Snippets]]

Revision as of 21:56, 10 March 2008

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"