Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append char to an existing string Objective - C

Tags:

objective-c

I'm trying to append and programmatically modify a NSString on the fly. I'd like to know a couple of things:

  • How do I modify specific chars in a defined NSString?
  • How do I add chars in a defined NSString?

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?

like image 231
locoboy Avatar asked Dec 04 '22 22:12

locoboy


2 Answers

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
like image 145
Jhaliya - Praveen Sharma Avatar answered Dec 29 '22 00:12

Jhaliya - Praveen Sharma


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:).

like image 39
Bryan Irace Avatar answered Dec 28 '22 23:12

Bryan Irace