35

How do I insert a space to a NSString.

I need to add a space at index 5 into:

NString * dir = @"abcdefghijklmno";

To get this result:

abcde fghijklmno

with:

NSLOG (@"%@", dir);
stefanB
  • 77,323
  • 27
  • 116
  • 141
JohnPortella
  • 1,791
  • 5
  • 21
  • 30

6 Answers6

94

You need to use NSMutableString

NSMutableString *mu = [NSMutableString stringWithString:dir];
[mu insertString:@" " atIndex:5];

or you could use those method to split your string :

– substringFromIndex:
– substringWithRange:
– substringToIndex:

and recombine them after with

– stringByAppendingFormat:
– stringByAppendingString:
– stringByPaddingToLength:withString:startingAtIndex:

But that way is more trouble that it's worth. And since NSString is immutable, you would bet lot of object creation for nothing.


NSString *s = @"abcdefghijklmnop";
NSMutableString *mu = [NSMutableString stringWithString:s];
[mu insertString:@"  ||  " atIndex:5];
//  This is one option
s = [mu copy];
//[(id)s insertString:@"er" atIndex:7]; This will crash your app because s is not mutable
//  This is an other option
s = [NSString stringWithString:mu];
//  The Following code is not good
s = mu;
[mu replaceCharactersInRange:NSMakeRange(0, [mu length]) withString:@"Changed string!!!"];
NSLog(@" s == %@ : while mu == %@ ", s, mu);  
//  ----> Not good because the output is the following line
// s == Changed string!!! : while mu == Changed string!!! 

Which can lead to difficult to debug problems. That is the reason why @property for string are usually define as copy so if you get a NSMutableString, by making a copy you are sure it won't change because of some other unexpected code.

I tend to prefer s = [NSString stringWithString:mu]; because you don't get the confusion of copying a mutable object and having back an immutable one.

Andy Obusek
  • 12,614
  • 4
  • 41
  • 62
Vincent Bernier
  • 8,674
  • 4
  • 35
  • 40
4

And here, for example, is how to insert a space every 3 chars...

NSMutableString *mutableString = [NSMutableString new];
[mutableString setString:@"abcdefghijklmnop"];

for (int p = 0; p < [mutableString length]; p++) {
    if (p%4 == 0) {
        [mutableString insertString:@" " atIndex:p];
    }
}

NSLog(@"%@", mutableString);

result: abc def ghi jkl mno p

Mason Lee
  • 5,130
  • 1
  • 20
  • 15
Muruganandham K
  • 5,271
  • 5
  • 34
  • 62
3

For a simple task you need a simple solution:

NSString *text = @"abcdefghijklmno";
NSString *characterToInsert = @" ";
NSUInteger index = 5;
text = [@[[text substringToIndex:index], [text substringFromIndex:index]] componentsJoinedByString:characterToInsert];

And the Swift version (if anyone is interested):

var text = "abcdefghijklmno"
let characterToInsert = Substring(" ")
let index = text.index(text.startIndex, offsetBy: 5)
text = String(text[..<index] + characterToInsert + text[index...])
turingtested
  • 6,356
  • 7
  • 32
  • 47
2
NSMutableString *liS=[[NSMutableString alloc]init];  
for (int i=0; i < [dir length]; i++) 
{
    NSString *ichar  = [NSString stringWithFormat:@"%c", [lStr characterAtIndex:i]];
    [l1S appendString:ichar];
    if (i==5)  
    {
        [l1S appendString:@" "];
    }
}

dir=l1S;
NSLog(@"updated string is %@",dir);

Try this it will helps you

Vincent Bernier
  • 8,674
  • 4
  • 35
  • 40
KAREEM MAHAMMED
  • 1,675
  • 14
  • 38
0

On C++ I've found easier to manipulate a std::string and then converting that into a NSString. E.g.:

std::string text = "abcdefghijklmno";
text.insert(text.begin()+5, ' ');

NSString* result = [NSString stringWithUTF8String:text.c_str()];
dacap
  • 478
  • 3
  • 19
0

There is a solution without using a mutable string: replace the characters in a range with length 0:

NSString * test = @"1234";
// Insert before "3", which is at index 2.
NSRange range = NSMakeRange(2, 0);
NSString * inserted = [test stringByReplacingCharactersInRange:range 
    withString:@"abc"]
NSLog(@"%@", inserted); // 12abc34
DarkDust
  • 90,870
  • 19
  • 190
  • 224