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

时间:2015-05-28 06:48:15

标签: ios uitextview nsrange

我需要逐一突出UITextView中的单词。如何获取UITextView的所有单词的NSRange值并将其存储在NSArray

3 个答案:

答案 0 :(得分:3)

您可以使用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);

答案 1 :(得分:2)

编辑:此解决方案运行良好但是有点“硬路径”,并且在原始字符串中出现双倍空格时崩溃。 @ 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}" )

答案 2 :(得分:-1)

如果您打算在点击“返回”键后获取数组,则使用textfield委托方法

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