0

我需要获取 NSString 的单词或音节的位置(索引)。很抱歉我无法发布任何代码,因为我不知道从哪里开始。我正在使用网络服务,服务将在句子中回复我单词或音节,并告诉我任何颜色,我必须在句子中更改单词的颜色。我想出了如何改变字符的颜色,但我需要知道它的索引。我将非常感谢任何线索或帮助。提前致谢。

4

2 回答 2

3

要获取字符串中的单词,您可以调用:

    NSString *string = @"How to get index";
    NSArray *words = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"%lu",[words indexOfObject: @"get"]); // outputs 2 (starts at 0)

以音节分隔取决于语言,而且很难做到。

于 2013-10-02T11:39:20.970 回答
0

用索引枚举单词:

NSString *s = @"How to get index of word or syllable in NSString";
__block NSUInteger i = 0;
[s enumerateSubstringsInRange:NSMakeRange(0, [s length])
                      options:NSStringEnumerationByWords
                   usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                       NSLog(@"%lu %@", i++, substring);
                   }];

那将打印

0 How
1 to
2 get

等等

等效的方法是:

NSUInteger words = 0;
NSScanner *scanner = [NSScanner scannerWithString: s];
NSString *capture;
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
while ([scanner scanUpToCharactersFromSet:whiteSpace intoString:&capture]){
    NSLog(@"%lu %@", words++, capture);
}

但依赖于空格、制表符和换行符作为分隔符。第一种方法更好。

于 2013-10-02T11:40:20.537 回答