I'm trying to append and programmatically modify a NSString on the fly. I'd like to know a couple of things:
For example if I have the following defined: NSString *word = [[NSString alloc] initWithString:@"Hello"];
how would I be able to replace the letter "e" with "a" and also how would I add another char to the string itself?
Nerver use NSString
for string manipulation,Use NSMutableString
.
NSMutableString is the subclass of NSString and used for that purpose.
From Apple Documentation:
The NSString
class declares the programmatic interface for an object that manages immutable strings. (An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString
is implemented to represent an array of Unicode characters (in other words, a text string).
The mutable subclass of NSString is NSMutableString
.
NSMutableString *word = [[NSMutableString alloc] initWithString:@"Hello"];
//Replace a character
NSString* word2 = [word stringByReplacingOccurrencesOfString:@"e" withString:@"a"];
[word release];
word = nil ;
word = [[NSMutableString alloc] initWithString:word2 ];
//Append a Character
[word appendString:@"a"];
There are more string manipulating function See Apple Documentation for NSMutableString
Edited:
you could first use rangeOfString
to get the range of the string (in your case @"e").
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
then check the NSRange object if it's valid then use the replaceCharactersInRange
function on your NSMutableString
to replace the set of characters with your string.
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString
NSString instances are immutable. You can create new NSString instances by appending or replacing characters in another like this:
NSString *foo = @"Foo";
NSString *bar = @"Bar";
NSString *foobar = [foo stringByAppendingString:bar];
NSString *baz = [bar stringByReplacingOccurrencesOfString:@"r" withString:@"z"];
If you really need to modify an instance directly, you can use an NSMutableString instead of an NSString.
If you really want to use primitive characters, NSString has a couple of initializers that can take character arrays (e.g. initWithCharacters:length:
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With