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

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

    Unless you're going to be doing it hundreds of times a second, I would just opt for the readable solution, something like the following pseudocode:

    def count (str):
        lastchar = " "
        count = 0
        for char as every character in string:
            if char is not whitespace and lastchar is whitespace:
                count = count + 1
            lastchar = char
        return count
    

    It seems a bit of a waste to create a whole array of other strings just so you can count them and throw them away.

    And if, for some reason, it becomes an issue, you can just replace the function body with a faster version. Make sure it is a problem first however. Optimisation of code that's fast enough already is wasted effort.

提交回复
热议问题