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

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

//字符串匹配
- (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<NSString *> *indexArray = [self stringMatcher:beginStr string:string];
    for (NSString *str in indexArray) {
        int index = [str intValue];
        NSString *str = [string substringFromIndex:index + beginStr.length];
        NSArray<NSString *> *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;
}

实现效果:

效果

你可能感兴趣的:(ios,iphone)