/***********************************************************
@Execise:
统计字符串中单词的数目
@Notice:
1. NSRegularExpression 来自 Foundation
2. Swift 的异常捕捉写法很另类(哈哈哈,任性咯):
与大多数语言相比,执行可能出现异常的代码块用do,然后try放在代
码块中可能产生异常的代码开头,catch用来捕获异常
3. 判断是否单词的正则表达式:"\\w+"
***********************************************************/
import Foundation
func wordCount(_ string: String)->Int{
do {
//构造正则表达式
let regular = try NSRegularExpression(pattern: "\\w+", options: .caseInsensitive)
let matches = regular.matches(in: string, options: [], range: NSMakeRange(0, string.characters.count))
// 打印出所有单词
// for result in matches {
// print((string as NSString).substring(with: result.range))
// }
return matches.count
} catch _ {
return 0
}
}
let string = "A nonprofit organization (NPO) is an organization that uses surplus revenues to achieve its goals rather than distributing them as profit or dividends. The goals of an NPO are always to change or improve a social issue. NPOs use the model of a double bottom line in that furthering their cause is more important than making a profit though both are necessary to the organization's success. Although nonprofit organizations are permitted to generate surplus revenues, they must be retained by the organization for its self-preservation, expansion, or plans. NPOs have controlling members or a board of directors. Many have paid staff including management, whereas others employ unpaid volunteers and even executives who work with or without compensation (occasionally nominal). Where there is a token fee, in general, it is used to meet legal requirements for establishing a contract between the executive and the organization. Designation as a nonprofit does not mean that the organization does not intend to make a profit, but rather that the organization has no owners and that the funds realized in the operation of the organization will not be used to benefit any owners. The extent to which an NPO can generate surplus revenues may be constrained or use of surplus revenues may be restricted."
print(wordCount(string)) // 211
Swift练笔 —— 统计字符串中的单词数目
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...