たとえば、「a、b、c、d、e、f、g、h」などの文字列があります。インデックス4から始まり、インデックス6で終わるコンテンツを置き換えたいと思います。
したがって、例では、結果の文字列は「a、b、c、d、f、e、g、h」になります。
参考までに、置換するインデックスを含む動的なすべてのコンテンツのみ..
これを達成する方法がわかりません..どんな助けでも大歓迎です!!
あなたの例から、文字列内のコンポーネントを置き換えたいことがわかります(つまり、インデックス 4 は 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"
}
この場合、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.