//今天在做语音评测的时候,遇到了要给label上的字符串按单词得分配置不同颜色时,遇到获取单词range的问题。
iOS 通过字符串获取单词及range
NSString * str2 = @"Do the any the additional setup after loading the view, typically from a nib.";
[str2 enumerateSubstringsInRange:NSMakeRange(0, str2.length-1) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
NSLog(@"substring--- %@ range :%@", substring, NSStringFromRange(substringRange));
}];
输出:
substring--- Do range :{0, 2}
substring--- the range :{3, 3}
substring--- any range :{7, 3}
substring--- the range :{11, 3}
substring--- additional range :{15, 10}
substring--- setup range :{26, 5}
substring--- after range :{32, 5}
substring--- loading range :{38, 7}
substring--- the range :{46, 3}
substring--- view range :{50, 4}
substring--- typically range :{56, 9}
substring--- from range :{66, 4}
substring--- a range :{71, 1}
substring--- nib range :{73, 3}