2012-01-04 50 views
30

如何向NSString插入空格。如何在NSString中插入字符

我需要在索引5中添加的空間分爲:

NString * dir = @"abcdefghijklmno"; 

爲了得到這樣的結果:

abcde fghijklmno 

有:

NSLOG (@"%@", dir); 
+0

請詳細解釋您的問題.. – Hiren 2012-01-04 04:37:59

+0

我需要在NSString中添加一個字符(空格) – JohnPortella 2012-01-04 04:40:27

+0

可能的重複[如何連接字符串?](http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings) – pasawaya 2012-11-10 04:36:40

回答

77

您需要使用NSMutableString

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

,或者你可以用這些方法來分割你的字符串:

- substringFromIndex:
- substringWithRange:
- substringToIndex:

,並與後重新組合它們

- stringByAppendingFormat:
- 條帶gByAppendingString:
- 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];,因爲您沒有複製可變對象並返回不可變對象的混淆。

+0

This是好的,但你可以通過使用'mutableCopy'來縮短它。 'dir = [[dir mutableCopy] insertString:@「」atIndex:5];' – dasblinkenlight 2012-01-04 04:44:21

+0

那你可以這樣做嗎? dir = mu? – JohnPortella 2012-01-04 05:18:02

+0

@DUnkelheit - 編輯我的回答你的interogation – 2012-01-04 06:07:28

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

試試這個它會幫助你

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

1

對於一個簡單的任務,你需要一個簡單的解決方案:

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

在C++上,我發現操作std::string更容易,然後將其轉換爲NSString。例如:

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

NSString* result = [NSString stringWithUTF8String:text.c_str()]; 
相關問題