在Swift中查找字符串中的空格数

时间:2015-06-23 03:11:44

标签: ios string swift

我可以调用什么方法来查找Swift中字符串中的空格数。然后我想循环遍历这样的数字:

\w

谢谢!

3 个答案:

答案 0 :(得分:13)

Swift 4或更高版本

let str = "Hello, playground. Hello, playground !!!"
let spaceCount = str.filter{$0 == " "}.count
print(spaceCount) // 4

Swift 3

let spaceCount = str.characters.filter{$0 == " "}.count

答案 1 :(得分:3)

let title = "A sample string to test with."
let count = title.componentsSeparatedByString(" ").count - 1
print(count) // 5

答案 2 :(得分:1)

另一种方法可能是实现以下功能:

func nbSpacesIn(_ word: String) -> Int {
return String(word.unicodeScalars.filter({$0.value == 32})).count}