iPhone iOS如何计算字符串中不区分大小写的单词出现次数?

iPhone iOS如何计算字符串中不区分大小写的单词出现次数?,iphone,objective-c,ios,nsstring,keyword,Iphone,Objective C,Ios,Nsstring,Keyword,我正在寻找一种方法来搜索任意长字符串(10000个字符),并找到特定关键字在字符串中重复的次数。如何做到这一点 我有一个方法,它可以计算字符串围绕关键字拆分后留下的片段数量,但它不区分大小写 -(void)countKeywords { NSArray* components = [self.salesCopy componentsSeparatedByString:@"search term"]; NSLog(@"search term number found: %i",c

我正在寻找一种方法来搜索任意长字符串(10000个字符),并找到特定关键字在字符串中重复的次数。如何做到这一点

我有一个方法,它可以计算字符串围绕关键字拆分后留下的片段数量,但它不区分大小写

-(void)countKeywords
{
    NSArray* components = [self.salesCopy componentsSeparatedByString:@"search term"];

    NSLog(@"search term number found: %i",components.count);


}

计算字符串中关键字数量的更好方法是什么?

只需创建self.salesCopy和searchTerm的副本,通过[NSString lowercaseString]将副本设置为小写,然后执行代码,就可以进行计数

-(void)countKeywords
{
    NSString *lowerCaseSalesCopy = [self.salesCopy lowercaseString];
    NSString *lowerCaseSearchTerm = [searchTerm lowercaseString];
    NSArray* components = [lowerCaseSalesCopy componentsSeparatedByString:lowerCaseSearchTerm];

    NSLog(@"search term number found: %i",components.count);
}

我不是100%确定这能帮到你,但可能会做一些你需要的工作(如果不是全部):

看看

ran.length
ran.location

run.location将为您提供第一次出现的字符串中的位置。然后,您可以在此事件发生后剪切字符串,并再次运行此操作,直到字符串结束

拆分字符串、计算部分并将其丢弃是没有效率的。重复搜索子字符串而不创建新对象肯定会更有效。由于字符串相对较长,您可能会受益于实现高级字符串搜索算法,例如,显著缩短搜索时间

下面是一个应该比拆分代码更快的实现:

NSString *str = @"Hello sun, hello bird, hello my lady! Hello breakfast, May I buy you again tomorrow?";
NSRange r = NSMakeRange(0, str.length);
int count = 0;
for (;;) {
    r = [str rangeOfString:@"hello" options:NSCaseInsensitiveSearch range:r];
    if (r.location == NSNotFound) {
        break;
    }
    count++;
    r.location++;
    r.length = str.length - r.location;
}
NSLog(@"%d", count);

这将只返回字符串第一次出现的长度,海报将查找不区分大小写出现的总数。您是对的,但正如我提到的,这不是100%的解决方案。我会添加更多有帮助的信息。这是一个专业的答案!这看起来正是我要找的。我会在搜索之前将字符串转换为小写,以处理不区分大小写的问题。看起来解决方案已经在执行不区分大小写的搜索(
NSCaseInsensitiveSearch
),因此将字符串转换为小写是不必要的。非常好地捕捉到了小写转换,我忘记了该方法!
NSString *str = @"Hello sun, hello bird, hello my lady! Hello breakfast, May I buy you again tomorrow?";
NSRange r = NSMakeRange(0, str.length);
int count = 0;
for (;;) {
    r = [str rangeOfString:@"hello" options:NSCaseInsensitiveSearch range:r];
    if (r.location == NSNotFound) {
        break;
    }
    count++;
    r.location++;
    r.length = str.length - r.location;
}
NSLog(@"%d", count);