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

前端 未结 7 1954
我在风中等你
我在风中等你 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 05:59

    In this situation, I'd use an NSScanner like so:

    NSString *str = @"this is a string";
    NSScanner *scanner = [NSScanner scannerWithString:str];
    NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSCharacterSet *nonWhitespace = [whiteSpace invertedSet];
    int wordcount = 0;
    
    while(![scanner isAtEnd])
    {
        [scanner scanUpToCharactersFromSet:nonWhitespace intoString:nil];
        [scanner scanUpToCharactersFromSet:whitespace intoString:nil];
        wordcount++;
    }
    

    This only creates two additional objects, no matter how long the string is.

提交回复
热议问题