/***********************************************************
@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练笔 —— 统计字符串中的单词数目
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。