What is the most efficient way to count number of word in NSString without using regex?

前端 未结 7 1963
我在风中等你
我在风中等你 2020-12-20 05:31

I am a bit new to Objective C and was wondering if there is a better way to count words in a string.

ie:

NSString *str = @\"this is a string\";

// r         


        
7条回答
  •  难免孤独
    2020-12-20 06:05

    This code will count the number of words (i.e., non-empty substrings) contained in a string that are separated by any number of space or line break characters:

    NSUInteger wordCount = 0;
    
    for (NSString* word in [someString
        componentsSeparatedByCharactersInSet:
        [NSMutableCharacterSet characterSetWithCharactersInString:@" \n"]]) {
    
        if (![word  isEqual: @""]) {
            wordCount++;
        }
    
    }
    

    It's a slight improvement to zoul's answer without recurring to regexes.

提交回复
热议问题