如何获取数组中 UITextView 的所有单词的 NSRange 值?

How do I get the NSRange values of all the words of a UITextView in an array?

我需要在 UITextView 中一个一个地突出显示单词。如何获取 UITextView 中所有单词的 NSRange 值并将它们存储在 NSArray 中?

可以使用NSString的这个方法 - enumerateSubstringsInRange:options:usingBlock:,选项用NSStringEnumerationByWords。它将遍历字符串的所有单词并为您提供它的范围,您可以将其保存到数组中。

NSString *string = @"How do I get the NSRange values of all the words of a UITextView in an array";

NSMutableArray *words = [NSMutableArray array];
NSMutableArray *ranges = [NSMutableArray array];

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByWords
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                            [words addObject:substring];
                            [ranges addObject:[NSValue valueWithRange:substringRange]];
                        }
 ];

NSLog(@"Words:\n%@", words);
NSLog(@"Ranges:\n%@", ranges);

如果您打算在按下 "Return" 键后获取数组,请使用文本字段委托方法

-(void)textFieldDidEndEditing:(UITextField *)textField{
NSArray *allwords = [textField.text componentsSeparatedByString:@" "];
}

编辑: 此解决方案效果很好,但有点像 "hard way",并且在原始字符串中出现双空格时会崩溃。 @pteofil 使用 enumerateSubstringsInRange:options:usingBlock: 的解决方案更干净。


这应该可以完成工作,即使字符串中有重复的单词:

// Your original text, which you should access with myTextView.text
NSString *text = @"Hello world this is a text with duplicated text string inside";

// Arrays to store separate words and ranges
NSArray *words = [text componentsSeparatedByString:@" "];
NSMutableArray *ranges = [NSMutableArray array];

// The search range, in case your text contains duplicated words
NSRange searchRange = NSMakeRange(0, text.length);

// Loop on the words
for (NSString *word in words) {

    // Get the range of the word, /!\ in the search range /!\
    NSRange range = [text rangeOfString:word options:NSLiteralSearch range:searchRange];
    // Store it in an NSValue, as NSRange is not an object
    // (access the range later with aValue.rangeValue
    [ranges addObject:[NSValue valueWithRange:range]];
    // Set your new search range to after the last word found, to avoid duplicates
    searchRange = NSMakeRange(range.location + range.length, text.length - (range.location + range.length));
}

// Logging the results
NSLog(@"Text:\n%@", text);
NSLog(@"Words:\n%@", words);
NSLog(@"Ranges:\n%@", ranges);

这给出了以下输出:

Text: 
Hello world this is a text with duplicated text string inside

Words:
(
    Hello,
    world,
    this,
    is,
    a,
    text,
    with,
    duplicated,
    text,
    string,
    inside )

Ranges:
(
    "NSRange: {0, 5}",
    "NSRange: {6, 5}",
    "NSRange: {12, 4}",
    "NSRange: {17, 2}",
    "NSRange: {20, 1}",
    "NSRange: {22, 4}",
    "NSRange: {27, 4}",
    "NSRange: {32, 10}",
    "NSRange: {43, 4}",
    "NSRange: {48, 6}",
    "NSRange: {55, 6}" )