NSStringに文字を挿入する方法 質問する

NSStringに文字を挿入する方法 質問する

NSString にスペースを挿入するにはどうすればいいですか。

インデックス 5 にスペースを追加する必要があります:

NString * dir = @"abcdefghijklmno";

この結果を得るには:

abcde fghijklmno

と:

NSLOG (@"%@", dir);

ベストアンサー1

使用する必要があるNSMutableString

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

または、これらのメソッドを使用して文字列を分割することもできます。

– サブ文字列からインデックス:
– サブ文字列の範囲:
– サブ文字列からインデックス:

そして、それらを再結合する

– 文字列による追加形式:
– 文字列による追加文字列:
– 文字列によるパディングの長さ:文字列による開始インデックス:

しかし、その方法は、価値に見合わないほど面倒です。また、は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];変更可能なオブジェクトをコピーして不変のオブジェクトを返すという混乱が起こらないため、私はこれを好む傾向があります。

おすすめ記事