2013-03-28 55 views
0

我有一個字符串,例如「a,b,c,d,e,f,g,h」,現在我想替換從索引4 &結尾開始的內容在索引6處。將NSString的中間內容替換爲其他內容

因此在例子中,結果字符串將是「a,b,c,d,f,e,g,h」。

FYI唯一的全動態內容包括索引被替換..

我不知道如何做到這一點..任何幫助表示讚賞!

+0

憑什麼你決定開始索引和結束索引更換? – Rushi 2013-03-28 05:30:22

+0

@Rushi它是動態的,我有一堆數據和填充後我會有初始字符串和當我想更新填滿數據我有一個臨時變量來決定在哪個索引我需要更新字符串使用臨時變量 – 2013-03-28 05:34:15

回答

1

看起來從您要在字符串替換部件的例子(即指數4是第四分隔的字母 - 的「E」)。如果是這樣的話,那麼解決的辦法是用的NSString componentsSeparatedByString:和componentsJoinedByString:

// string is a comma-separated set of characters. replace the chars in string starting at index 
// with chars in the passed array 

- (NSString *)stringByReplacingDelimitedLettersInString:(NSString *)string withCharsInArray:(NSArray *)chars startingAtIndex:(NSInteger)index { 

    NSMutableArray *components = [[string componentsSeparatedByString:@","] mutableCopy]; 

    // make sure we start at a valid position 
    index = MIN(index, components.count-1); 

    for (int i=0; i<chars.count; i++) { 
     if (index+i < components.count) 
      [components replaceObjectAtIndex:index+i withObject:chars[i]]; 
     else 
      [components addObject:chars[i]]; 
    } 
    return [components componentsJoinedByString:@","]; 
} 

- (void)test { 
    NSString *start = @"a,b,c,d,e,f,g"; 
    NSArray *newChars = [NSArray arrayWithObjects:@"x", @"y", @"y", nil]; 
    NSString *finish = [self stringByReplacingDelimitedLettersInString:start withCharsInArray:newChars startingAtIndex:3]; 
    NSLog(@"%@", finish); // logs @"a,b,c,x,y,z,g" 

    finish = [self stringByReplacingDelimitedLettersInString:start withCharsInArray:newChars startingAtIndex:7]; 
    NSLog(@"%@", finish); // logs @"a,b,c,d,e,f,x,y,z" 
} 
1

在這種情況下,最好是NSMutableString。請看下面的例子:

int a = 6; // Assign your start index. 
int b = 9; // Assign your end index. 

NSMutableString *abcd = [NSMutableString stringWithString:@"abcdefghijklmano"]; // Init the NSMutableString with your string. 
[abcd deleteCharactersInRange:NSMakeRange(a, b)]; //Now remove the charachter in your range. 

[abcd insertString:@"new" atIndex:a]; //Insert your new string at your start index. 
+0

爲什麼我不能使用replaceCharactersInRange? – 2013-03-28 06:01:35

+0

是的,你也可以replaceCharactersInRange。它會在一個聲明中完成你的任務。 – Rushi 2013-03-28 06:03:36