什么是最有效的方式来计算NSString中的字数,而不使用regex? [英] What is the most efficient way to count number of word in NSString without using regex?

查看:73
本文介绍了什么是最有效的方式来计算NSString中的字数,而不使用regex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective C有点陌生,想知道是否有更好的方法来计算字符串中的字词。

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";

// return should be 4 words ..

如何做到这一点是通过将字符串打断成数组的字空格('')字符和计数数组。

The way I now how to do it is by breaking the string into an array of words space (' ') character and count the array.

任何建议都将不胜感激!谢谢!! :)

Any advise will be appreciated! Thanks!! :)

编辑:
对于那些来到这里寻找答案的人:我发现了一个类似的帖子,回复很好。

For those of you who came here looking for answer; I found a similar post with an excellent reply.

http://stackoverflow.com/questions/2266434/how-to-count-words-withina-a-text-string

$

b
$ b

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.

这篇关于什么是最有效的方式来计算NSString中的字数,而不使用regex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆