美文网首页iOS随笔
iOS如何截取字符串中某个字符出现第N次时的字符串

iOS如何截取字符串中某个字符出现第N次时的字符串

作者: 095b62ead3cd | 来源:发表于2018-06-14 12:36 被阅读274次

    举例:

    NSString *str = @"DISTRICT-00001-00001-00005-00020";
    

    如何将上述字符串的第三个"-"前内容截取出来?

    一、这种最常见的做法是将字符串分割然后拼接如下:

    NSString *str = @"DISTRICT-00001-00001-00005-00020";
        NSArray *arr = [str componentsSeparatedByString:@"-"];
        NSString *newStr = [NSString stringWithFormat:@"%@-%@-%@",arr[0],arr[1],arr[2]];
        NSLog(@"%@====%@",arr,newStr);
    

    结果如下:

    2018-06-14 12:13:08.494293+0800 test[9145:1108895] (
        DISTRICT,
        00001,
        00001,
        00005,
        00020
    )====DISTRICT-00001-00001
    

    这样做就比较繁琐一点,而且假如字符串比较长,这样的方法就不是很方便了

    二、先遍历字符串找到所有的@"-"所在的位置的index,然后通过index将字符串进行截取。具体方法如下:

    - (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText{
        NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
        if (findText == nil && [findText isEqualToString:@""]){
            return nil;
        }
        NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
        if (rang.location != NSNotFound && rang.length != 0){
            [arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
            NSRange rang1 = {0,0};
            NSInteger location = 0;
            NSInteger length = 0;
            for (int i = 0;; i++){
                if (0 == i){
                    location = rang.location + rang.length;
                    length = text.length - rang.location - rang.length;
                    rang1 = NSMakeRange(location, length);
                }else{
                    location = rang1.location + rang1.length;
                    length = text.length - rang1.location - rang1.length;
                    rang1 = NSMakeRange(location, length);
                }
                //在一个range范围内查找另一个字符串的range
                rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
                if (rang1.location == NSNotFound && rang1.length == 0){
                    break;
                }
                else{
                    //添加符合条件的location进数组
                    [arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
                }
            }
            return arrayRanges;
        }
        return nil;
    }
    
    NSMutableArray *array = [self getRangeStr:str findText:@"-"];
        NSLog(@"array:%@",array);
        NSString *newString = [str substringToIndex:20];
        NSLog(@"newString:%@",newString);
    
    

    结果如下:

    2018-06-14 12:34:30.102458+0800 test[9233:1119637] array:(
        8,
        14,
        20,
        26
    )
    2018-06-14 12:34:30.102480+0800 test[9233:1119637] newString:DISTRICT-00001-00001
    

    相关文章

      网友评论

        本文标题:iOS如何截取字符串中某个字符出现第N次时的字符串

        本文链接:https://www.haomeiwen.com/subject/nxtyeftx.html