Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating strings in Objective-C

I have a NSString with 10 characters. I need to add a dash - at character position 4 and 8. What is the most efficient way to do this? thanks

like image 979
lisa Avatar asked Sep 08 '26 23:09

lisa


2 Answers

You need a mutable string, not a NSString.

NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];

Fixed code based on stko's answer, which is bug free.

like image 179
Derrick Avatar answered Sep 11 '26 02:09

Derrick


You should take care to insert the dash at the highest index first. If you insert at index 4 first, you will need to insert at index 9 instead of 8 for the second dash.

e.g. This does not produce the desired string...

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];

[s insertString:@"-" atIndex:4];  // s is now @"abcd-efghij"
[s insertString:@"-" atIndex:8];  // s is now @"abcd-efg-hij"

While this one does:

NSMutableString *s = [NSMutableString stringWithString:@"abcdefghij"];

[s insertString:@"-" atIndex:8];  // s is now @"abcdefgh-ij"
[s insertString:@"-" atIndex:4];  // s is now @"abcd-efgh-ij"
like image 45
stko Avatar answered Sep 11 '26 02:09

stko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!