Niru Mukund Shah
Niru Mukund Shah

Reputation: 4733

Replace middle contents of NSString with other content

I have a string say for example "a,b,c,d,e,f,g,h" , Now I want to replace content which is starting from index 4 & ending at index 6.

So in example the resulting string will be "a,b,c,d,f,e,g,h".

FYI only all the content in dynamic including the indexes to be replace..

I've no idea how to achieve this.. Any help is appreciated!!

Upvotes: 0

Views: 122

Answers (2)

danh
danh

Reputation: 62686

It looks from your example that you want to replace components in the string (i.e. index 4 is the fourth delimited letter - the 'e'). If that's the case, then the solution lies with NSString componentsSeparatedByString: and 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"
}

Upvotes: 1

Rushi
Rushi

Reputation: 4500

In this case it's better if you NSMutableString. See the following example:

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.

Upvotes: 1

Related Questions