我有一个字符串,例如 "a,b,c,d,e,f,g,h" ,现在我想替换从索引 4 开始并以索引 6 结束的内容。
因此,在示例中,结果字符串将是“a,b,c,d,f,e,g,h”。
仅供参考,只有动态的所有内容,包括要替换的索引。
我不知道如何做到这一点..任何帮助表示赞赏!
在这种情况下,最好是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.
从您的示例中可以看出您想要替换字符串中的组件(即索引 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"
}