用其他内容替换NSString的中间内容

时间:2013-03-28 05:27:58

标签: iphone nsstring

我有一个字符串说例如“a,b,c,d,e,f,g,h”,现在我想要替换从索引4&以指数6结束。

因此,在示例中,结果字符串将是“a,b,c,d,f,e,g,h”。

仅限FYI动态中的所有内容,包括要替换的索引..

我不知道如何实现这一点..感谢任何帮助!!

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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"
}