2010-09-13 86 views
3

我有一個NSMutableString包含一個字兩次(例如/ abc ....................../ABC)。如何替換字符串發生在另一個字符串的NSMutableString中

現在我想用/ xyz替換這兩個出現的/ abc。我只想替換第一次和最後一次發生的其他事件。

- (NSUInteger)replaceOccurrencesOfString:(NSString *)target 
           withString:(NSString *)replacement 
            options:(NSStringCompareOptions)opts 
            range:(NSRange)searchRange 

我發現這個NSMutableString的實例方法,但我不能在我的情況下使用它。 任何人有任何解決方案?

+0

這是一個網址?如果是這樣,你可以在NSURL中使用一堆方法(「URLByDeletingLastPathComponent」,例如:http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSURL_Class/Reference/Reference .html#// apple_ref/occ/instm/NSURL/URLByDeletingLastPathComponent) – 2010-09-13 09:58:10

+0

不,它不是NSURL它只是一個NSMutableString。 – 2010-09-13 10:02:45

回答

5

您可以先找到兩個範圍,然後替換它們seperately:

NSMutableString *s = [NSMutableString stringWithString:@"/abc asdfpjklwe /abc"]; 

NSRange a = [s rangeOfString:@"/abc"]; 
NSRange b = [s rangeOfString:@"/abc" options:NSBackwardsSearch]; 

if ((a.location == NSNotFound) || (b.location == NSNotFound)) { 
    // at least one of the substrings not present 
} else { 
    [s replaceCharactersInRange:a withString:@"/xyz"]; 
    [s replaceCharactersInRange:b withString:@"/xyz"]; 
} 
+0

它給出了例外 - 「超出範圍」。當我檢查a和b的值時,它會給出一些垃圾值(22666222)。 – 2010-09-13 11:07:01

+0

@Greshi:記得檢查'NSNotFound'。 – 2010-09-13 11:30:37

相關問題