简体   繁体   English

删除给定NSRange的子字符串

[英]Delete a sub string given a NSRange

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

这也应该做的伎俩:

NSString *result = [baseString stringByReplacingCharactersInRange:range withString:@""];

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. 您也可以将其转换为NSMutableString,并使用-deleteCharactersInRange:方法来完成此操作。

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

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. 也许你可以使用这段代码:这会查看一个包含代码的列表: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;

            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM