2012-12-27 60 views
0
NSString * myText = @"This is my really long text view"; 
NSUInterger textLenght = [myText length]; //NSLog 32 

如何在所選長度位置插入任何文本。例如,長度爲10?cocoa-touch如何將字符串插入到字符串中的特定長度位置

我試過,但它不工作!

NSRange textRange = [myText rangeOfComposedCharacterSequenceAtIndex:10]; 
[myText stringByReplacingCharactersInRange:textRange withString:@"NEW"]; 
+0

[NSString的問題]的可能重複(http://stackoverflow.com/questions/4551214/nsstring-question) – Caleb

回答

3

它分配:

myText=[myText stringByReplacingCharactersInRange:textRange withString:@"NEW"]; 

一個的NSString是不可改變的,你不能改變它的人物,這就是爲什麼stringByReplacingCharactersInRange不重新排列字符,但返回從零開始建立另一個字符串。

統籌考慮使用NSMutableString

NSMutableString * myText = [[NSMutableString alloc]initWithString: @"This is my really long text view"]; 
NSRange textRange = [myText rangeOfComposedCharacterSequenceAtIndex:10]; 
[myText replaceCharactersInRange: textRange withString:@"NEW"]; 
+0

謝謝!我不認爲這很容易! >「< – gunhi

+0

@gunhi不要忘記標記答案爲可接受。:-) –

相關問題