需求:
将随机字符串(用户手动输入的),例如 @"#好的话的哈哈 #哈哈哈,和大河 #很多哈哈的&#开导开导可#好的话的哈哈呵呵呵 #可控####123"
检索出以 @"#" 开头,以 @"~@#¥$%&×-=+·_+~*÷ ,。、;!‘’【】、《》?:“”「」|()……—— ,./;'[] \ <>?:"{}|!()…— " 结尾的标签;
类抖音将话题标为黄色,话题标签位置和长度已经标出,富文本功能很简单,本篇不再多加赘述。
代码
NSString *allStr = @"#好的话的哈哈 #哈哈哈,和大河 #很多哈哈的&#开导开导可#好的话的哈哈呵呵呵 #可控####123"; NSString *startStr = @"#"; NSString *endStr = @"~@#¥$%&×-=+·_+~*÷ ,。、;!‘’【】、《》?:“”「」|()……—— ,./;'[] \ <>?:"{}|!()…— "; NSMutableArray *subStrArray = [[NSMutableArray alloc] init]; int start = 0; int end = 0; BOOL isStart = NO; NSString *subStr = @""; for (int i=1; i<allStr.length; i++) { NSString *curStr = [allStr substringWithRange:NSMakeRange(i, 1)]; NSString *preStr = [allStr substringWithRange:NSMakeRange(i-1, 1)]; if (!isStart) { if (![endStr containsString:curStr] && [startStr containsString:preStr]) { isStart = YES; start = i-1; end = i-1; continue; } } if ([endStr containsString:curStr] || i==allStr.length-1) { end = i; } if (end > start && isStart) { int length = 0; if (end == allStr.length-1 && ![endStr containsString:curStr]) { length = end-start+1; } else { length = end-start; } subStr = [allStr substringWithRange:NSMakeRange(start, length)]; NSMutableDictionary *subStrDic = [[NSMutableDictionary alloc] init]; [subStrDic setObject:[NSString stringWithFormat:@"%d",start] forKey:@"start"]; [subStrDic setObject:[NSString stringWithFormat:@"%d",length] forKey:@"length"]; [subStrDic setObject:subStr forKey:@"subStr"]; [subStrArray addObject:subStrDic]; NSLog(@"%d %d %@",start,end,subStr); isStart = NO; } } NSLog(@"%@",subStrArray);
结果:
2020-12-04 16:10:39.657950+0800 Test[46210:8236403] 0 7 #好的话的哈哈 2020-12-04 16:10:39.658085+0800 Test[46210:8236403] 8 12 #哈哈哈 2020-12-04 16:10:39.658255+0800 Test[46210:8236403] 17 23 #很多哈哈的 2020-12-04 16:10:39.658381+0800 Test[46210:8236403] 24 30 #开导开导可 2020-12-04 16:10:39.658540+0800 Test[46210:8236403] 30 40 #好的话的哈哈呵呵呵 2020-12-04 16:10:39.658637+0800 Test[46210:8236403] 41 44 #可控 2020-12-04 16:10:39.658742+0800 Test[46210:8236403] 47 50 #123 2020-12-04 16:10:39.658911+0800 Test[46210:8236403] ( { length = 7; start = 0; subStr = "#U597dU7684U8bddU7684U54c8U54c8"; }, { length = 4; start = 8; subStr = "#U54c8U54c8U54c8"; }, { length = 6; start = 17; subStr = "#U5f88U591aU54c8U54c8U7684"; }, { length = 6; start = 24; subStr = "#U5f00U5bfcU5f00U5bfcU53ef"; }, { length = 10; start = 30; subStr = "#U597dU7684U8bddU7684U54c8U54c8U5475U5475U5475"; }, { length = 3; start = 41; subStr = "#U53efU63a7"; }, { length = 4; start = 47; subStr = "#123"; } )