1. 程式人生 > >iOS 查詢子字串在父字串中的所有位置

iOS 查詢子字串在父字串中的所有位置

/**
 改變UILabel部分字元顏色
 */
- (void)setContentLabelColor {
    NSString *content = @"2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格\n2018-08-27\n寫部落格";
    NSMutableArray *locationArr = [self calculateSubStringCount:content str:@"\n"];
    NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc] initWithString:content];
    for (int i=0; i<locationArr.count; i++) {
        if (i%2==0) {
            NSNumber *location = locationArr[i];
            [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0f/255.0f green:45.0f/255.0f blue:81.0f/255.0f alpha:1.0f] range:NSMakeRange(location.integerValue-10, 10)];//改變\n前邊的10位字元顏色,
        }
    }
    self.contentLabel.attributedText = attstr;
}

/**
 查詢子字串在父字串中的所有位置

 @param content 父字串
 @param tab 子字串
 @return 返回位置陣列
 */
- (NSMutableArray*)calculateSubStringCount:(NSString *)content str:(NSString *)tab {
    int location = 0;
    NSMutableArray *locationArr = [NSMutableArray new];
    NSRange range = [content rangeOfString:tab];
    if (range.location == NSNotFound){
        return locationArr;
    }
    //宣告一個臨時字串,記錄擷取之後的字串
    NSString * subStr = content;
    while (range.location != NSNotFound) {
        if (location == 0) {
            location += range.location;
        } else {
            location += range.location + tab.length;
        }
        //記錄位置
        NSNumber *number = [NSNumber numberWithUnsignedInteger:location];
        [locationArr addObject:number];
        //每次記錄之後,把找到的字串擷取掉
        subStr = [subStr substringFromIndex:range.location + range.length];
        NSLog(@"subStr %@",subStr);
        range = [subStr rangeOfString:tab];
        NSLog(@"rang %@",NSStringFromRange(range));
    }
    return locationArr;
}

效果圖: