/***********************************************************
@Execise:
統(tǒng)計字符串中單詞的數(shù)目
@Notice:
1. NSRegularExpression 來自 Foundation
2. Swift 的異常捕捉寫法很另類(哈哈哈涩赢,任性咯):
與大多數(shù)語言相比撕予,執(zhí)行可能出現(xiàn)異常的代碼塊用do稚配,然后try放在代
碼塊中可能產(chǎn)生異常的代碼開頭,catch用來捕獲異常
3. 判斷是否單詞的正則表達式:"\\w+"
***********************************************************/
import Foundation
func wordCount(_ string: String)->Int{
do {
//構(gòu)造正則表達式
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練筆 —— 統(tǒng)計字符串中的單詞數(shù)目
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門驴剔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人庸毫,你說我怎么就攤上這事∩婪” “怎么了飒赃?”我有些...
- 文/不壞的土叔 我叫張陵利花,是天一觀的道長。 經(jīng)常有香客問我载佳,道長炒事,這世上最難降的妖魔是什么? 我笑而不...
- 正文 為了忘掉前任蔫慧,我火速辦了婚禮挠乳,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘姑躲。我一直安慰自己睡扬,他們只是感情好,可當我...
- 文/花漫 我一把揭開白布黍析。 她就那樣靜靜地躺著卖怜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪阐枣。 梳的紋絲不亂的頭發(fā)上马靠,一...
- 文/蒼蘭香墨 我猛地睜開眼锁孟,長吁一口氣:“原來是場噩夢啊……” “哼彬祖!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起品抽,我...
- 正文 年R本政府宣布疏尿,位于F島的核電站,受9級特大地震影響易桃,放射性物質(zhì)發(fā)生泄漏褥琐。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一晤郑、第九天 我趴在偏房一處隱蔽的房頂上張望敌呈。 院中可真熱鬧,春花似錦造寝、人聲如沸磕洪。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽褐鸥。三九已至,卻和暖如春赐稽,著一層夾襖步出監(jiān)牢的瞬間叫榕,已是汗流浹背。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 1 尼采說:對待生命,你不妨大膽一點吐绵,因為我們始終要失去它迹淌! 有人說:要么死,要么精彩的活己单。 畏畏縮縮唉窃,謹小慎微是...
- 我出生在一個普通工薪家庭,和其它普通家庭的父母一樣廷痘,他們很愛我蔓涧,同時也非常希望我能有朝一日能成為他們的驕傲削咆。 典型...