代码之家  ›  专栏  ›  技术社区  ›  Abhinav

删除给定NSRange的子字符串

  •  10
  • Abhinav  · 技术社区  · 14 年前

    给定一个字符串和一个范围,是否有任何简单的方法可以通过从字符串中删除传递范围内的字符来获取子字符串?

    3 回复  |  直到 14 年前
        1
  •  33
  •   JustSid    14 年前

    这也可以做到:

    NSString *result = [baseString stringByReplacingCharactersInRange:range withString:@""];
    
        2
  •  3
  •   kennytm    14 年前

    您可以将子字符串放在范围的开头,将子字符串放在范围的结尾,并将它们连接在一起。

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

    the -deleteCharactersInRange: method 就是这样。

    NSString* stringByRemovingRange(NSString* theString, NSRange theRange) {
      NSMutableString* mstr = [theString mutableCopy];
      [mstr deleteCharactersInRange:theRange];
      return [mstr autorelease];
    }
    
        3
  •  -2
  •   meersmans    14 年前

    也许你可以用这段代码: 这将查看一个包含代码的列表:a、b、c、d,。。。 如果最后一个代码是d。。它将添加代码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;
    
                }
            }