Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a sub string given a NSRange

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?

like image 591
Abhinav Avatar asked Oct 21 '10 18:10

Abhinav


2 Answers

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];
}
like image 88
kennytm Avatar answered Nov 02 '22 13:11

kennytm


This should also do the trick:

NSString *result = [baseString stringByReplacingCharactersInRange:range withString:@""];
like image 26
JustSid Avatar answered Nov 02 '22 12:11

JustSid