如何将字符插入NSString

时间:2012-01-04 04:36:04

标签: objective-c ios5 nsstring

如何向NSString插入空格。

我需要在索引5处添加一个空格:

NString * dir = @"abcdefghijklmno";

要获得此结果:

abcde fghijklmno

使用:

NSLOG (@"%@", dir);

6 个答案:

答案 0 :(得分:85)

您需要使用NSMutableString

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

或者您可以使用这些方法来拆分字符串:

  

- substringFromIndex:
   - substringWithRange:
   - substringToIndex:

并用

重新组合它们
  

- stringByAppendingFormat:
   - stringByAppendingString:
   - stringByPaddingToLength:withString:startingAtIndex:

但这种方式更值得一试。而且由于NSString是不可变的,你会打赌很多对象都是无用的。


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!!! 

这可能导致难以调试的问题。 这就是为什么@property字符串通常被定义为copy的原因所以如果你得到一个NSMutableString,通过复制你肯定它不会因为其他一些意外的代码而改变

我倾向于选择s = [NSString stringWithString:mu];,因为你不会混淆复制一个可变对象并拥有一个不可变对象。

答案 1 :(得分:4)

在这里,例如,如何每隔3个字符插入一个空格......

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);

结果:abc def ghi jkl mno p

答案 2 :(得分: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);

试试这个会帮助你

答案 3 :(得分:1)

对于一项简单的任务,您需要一个简单的解决方案:

NString * dir = @"abcdefghijklmno";
NSUInteger index = 5;
dir = [@[[dir substringToIndex:index],[dir substringFromIndex:index]]componentsJoinedByString:@" "];

答案 4 :(得分:0)

在C ++上,我发现更容易操纵NSString,然后将其转换为std::string text = "abcdefghijklmno"; text.insert(text.begin()+5, ' '); NSString* result = [NSString stringWithUTF8String:text.c_str()]; 。 E.g:

PNUM = Sheets("Packing Slip").Cells(15, 5)

答案 5 :(得分:0)

有一个不使用可变字符串的解决方案:替换长度为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