在开发的过程中可能会遇到富文本展示,例如:一行文本,前面是题后面是答案,题和答案用不同的颜色字体,但是答案的内容在题总也有,这时候用平常的方法就会展示错误,因为把题中的内容改变了颜色二实际答案却没有改变颜色。需要把相同内容的rang放到数组里然后取最后一个rang就可以了。提供一个获得相同内容的rang的数组。
#pragma mark - 获取某个子字符串在某个总字符串中位置数组 /** * 获取某个字符串中子字符串的位置数组 * * @param totalString 总的字符串 * @param subString 子字符串 * * @return 位置数组 */ + (NSMutableArray *)ls_getRangeWithTotalString:(NSString *)totalString SubString:(NSString *)subString { NSMutableArray *arrayRanges = [NSMutableArray array]; if (subString == nil && [subString isEqualToString:@""]) { return nil; } NSRange rang = [totalString rangeOfString:subString]; if (rang.location != NSNotFound && rang.length != 0) { [arrayRanges addObject:[NSNumber valueWithRange:rang]]; NSRange rang1 = {0,0}; NSInteger location = 0; NSInteger length = 0; for (int i = 0;; i++) { if (0 == i) { location = rang.location + rang.length; length = totalString.length - rang.location - rang.length; rang1 = NSMakeRange(location, length); } else { location = rang1.location + rang1.length; length = totalString.length - rang1.location - rang1.length; rang1 = NSMakeRange(location, length); } rang1 = [totalString rangeOfString:subString options:NSCaseInsensitiveSearch range:rang1]; if (rang1.location == NSNotFound && rang1.length == 0) { break; } else { [arrayRanges addObject:[NSNumber valueWithRange:rang1]]; } } return arrayRanges; } return nil; }