類抖音#話題釋出視訊功能開發 字串檢索標籤(#開頭特殊字元結尾) iOS
阿新 • • 發佈:2020-12-04
需求:
將隨機字串(使用者手動輸入的),例如@"#好的話的哈哈 #哈哈哈,和大河 #很多哈哈的&#開導開導可#好的話的哈哈呵呵呵 #可控####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 = "#\U597d\U7684\U8bdd\U7684\U54c8\U54c8"; }, { length = 4; start = 8; subStr = "#\U54c8\U54c8\U54c8"; }, { length = 6; start = 17; subStr = "#\U5f88\U591a\U54c8\U54c8\U7684"; }, { length = 6; start = 24; subStr = "#\U5f00\U5bfc\U5f00\U5bfc\U53ef"; }, { length = 10; start = 30; subStr = "#\U597d\U7684\U8bdd\U7684\U54c8\U54c8\U5475\U5475\U5475"; }, { length = 3; start = 41; subStr = "#\U53ef\U63a7"; }, { length = 4; start = 47; subStr = "#123"; } )