NSString:在索引处查找单词范围



我已经尝试了一些算法,但没有运气解决这个问题。

让我们用一个例子进一步解释

行为

我们有一个字符串:@"example example"

因此,如果我在字符串上调用 rangeOfWordAtIndex:10

结果将是:单词@"example"位置 9,长度为 7。

它不应该给@"example" at index 0 with a length of 7.

这是我到目前为止生成的代码:

#define unicode_space 32 // this is correct printed it out from code
@implementation NSString (wordAt)
- (NSRange) rangeOfWordAtIndex:(NSInteger) index
{
    NSInteger beginIndex = index;
    while(beginIndex > 0 && [self characterAtIndex:beginIndex-1] != unicode_space)
    {
        beginIndex--;
    }
    NSInteger endIndex = index;
    NSInteger sLenght = [self length];
    while (endIndex < sLenght && [self characterAtIndex:endIndex+1] != unicode_space)
    {
        endIndex++;
    }
    return NSMakeRange(beginIndex, endIndex - beginIndex);
}
@end

但它就是不起作用。 如果没有 +1 和 -1,它会保留一个空格作为单词的一部分。

随之而来的是忘记了这个词的第一个字符。

有人可以给出一些有用的建议吗?

检测单词比查找U+0020 SPACE字符要复杂一些。幸运的是,Foundation为NSLinguisticTagger类提供了完整的Unicode支持。以下是您查找单词及其在给定索引处的范围的方法:

目标-C

NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:@[ NSLinguisticTagSchemeTokenType ] options:kNilOptions];
tagger.string = @"Hello, World!";
NSRange range = NSMakeRange(0, 0);
NSString *tag = [tagger tagAtIndex:10 scheme:NSLinguisticTagSchemeTokenType tokenRange:&range sentenceRange:nil];
if ([tag isEqualToString:NSLinguisticTagWord]) {
    NSString *word = [tagger.string substringWithRange:range];
    // You have the word: "World"
}
else {
    // Punctuation, whitespace or other.
}

迅速

let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeTokenType], options: 0)
tagger.string = "Hello, World!"
var range : NSRange = NSRange(location: 0, length: 0)
let tag = tagger.tagAtIndex(10, scheme: NSLinguisticTagSchemeTokenType, tokenRange: &range, sentenceRange: nil)
if let string = tagger.string where tag == NSLinguisticTagWord {
    let word = (string as NSString).substringWithRange(range)
    // You have the word: "World"
}
else {
    // Punctuation, whitespace or other.
}

最新更新