views:

33

answers:

3

Given a String and a Range is there any easy method to get a substring by removing the characters from String which come in the passed Range?

+1  A: 

You could get the substring to the start of the range, and the substring from the end of the range, and concatenate them together.

NSString* stringByRemovingRange(NSString* theString, NSRange theRange) {
  NSString* part1 = [theString substringToIndex:theRange.location];
  NSString* part2 = [theString substringFromIndex:theRange.location+theRange.length];
  return [part1 stringByAppendingString:part2];
}

You could also turn it into an NSMutableString, and use the -deleteCharactersInRange: method which does this exactly.

NSString* stringByRemovingRange(NSString* theString, NSRange theRange) {
  NSMutableString* mstr = [theString mutableCopy];
  [mstr deleteCharactersInRange:theRange];
  return [mstr autorelease];
}
KennyTM
+4  A: 

This should also do the trick:

NSString *result = [baseString stringByReplacingCharactersInRange:range withString:@""];
JustSid
Yes. This worked. Thanks!!!
Abhinav
A: 

Maybe you can use this piece of code: This looks into a list which has a code: a,b,c,d,... and if the last code is a d.. it will add the code e.

NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSUInteger i, count = [lead count];
    for (i = 0; i < count; i++) {
        Listings * l = [lead objectAtIndex:i];
        NSUInteger location = [alphabet rangeOfString:l.code].location + 1;
        if(!([l.code isEqualToString:@"X"]))
        {
            if(!(location -1 == i))
            {
                NSRange range = {location - 2,1};
                NSString *newCode = [alphabet substringWithRange:range];
                l.code = newCode;

            }
        }
meersmans