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

前端 未结 7 1932
我在风中等你
我在风中等你 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:16

    Are you sure you have a bottleneck in that part of code? If not (which is quite probable), then splitting on spaces seems perfectly acceptable to me. You could create a C string and count the spaces instead, but a lot of times such an “optimized” version is actually slower than the original one. That is, assuming that your current code looks like this:

    NSUInteger wordCount = [[someString componentsSeparatedByString:@" "] count];
    

    This is not exactly correct (see @"___" where underscore is a space), but maybe you really use a regex and split on \s+?

    0 讨论(0)
提交回复
热议问题