处理、获取两个字符串之间的字符串

处理、获取两个字符串之间的字符串:

//字符串匹配
- (NSArray *)stringMatcher:(NSString *)matchStr string:(NSString *)str{
    //在str中搜索matchStr并返回matchStr下标
    NSInteger matchStrLehgth = matchStr.length;
    NSInteger strLength = str.length;
    NSMutableArray *indexArray = [[NSMutableArray alloc]init];
    for (int index = 0; index <= (strLength - matchStrLehgth); index ++) {
        NSRange range = {index,matchStr.length};
        if ([matchStr isEqualToString:[str substringWithRange:range]]) {
            [indexArray addObject:[NSString stringWithFormat:@"%d",index]];
        }
    }
    return [NSArray arrayWithArray:indexArray];
}

//处理所有两个字符串中间的子串
- (NSMutableAttributedString *)findSubString:(NSString *)string beginStr:(NSString *)beginStr endStr:(NSString *)endStr{
    NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:string];
    NSDictionary *dic = @{NSFontAttributeName : [UIFont fontWithName:FontTypePingFangMe size:16]};
    
    NSArray *indexArray = [self stringMatcher:beginStr string:string];
    for (NSString *str in indexArray) {
        int index = [str intValue];
        NSString *str = [string substringFromIndex:index + beginStr.length];
        NSArray *endArray = [self stringMatcher:endStr string:str];
        if (endArray.count == 0) {
            return nil;
        }else{
            int endIndex = [endArray[0] intValue];
            NSRange range = {index + beginStr.length,(endIndex + index + beginStr.length) - (index + beginStr.length)};
            [attributed addAttributes:dic range:range];
        }
    }
    return attributed;
}

使用:

NSString *priceStr = @"拼团价¥888.88-¥999.99";
NSMutableAttributedString *attr = [self findSubString:priceStr beginStr:@"¥" endStr:@"."];
if (attr) {
    self.priceLabel.attributedText = attr;
}else{
    self.priceLabel.text = priceStr;
}

实现效果:

2个.png

无数个都可以.png

你可能感兴趣的:(处理、获取两个字符串之间的字符串)