在Swift中查找字符串中的空格数 [英] Find number of spaces in a string in Swift
本文介绍了在Swift中查找字符串中的空格数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Swift中我该调用什么方法来查找字符串中的空格数?我想遍历这个数字,像这样:
What method do I call to find the number of spaces in a string in Swift? I want to loop through that number, something like this:
@IBOutlet weak var stack: UILabel!
@IBOutlet weak var plus: UIButton!
@IBAction func sum(sender: AnyObject) {
var stackTitle = stack.text
var numberOfSpaces = stackTitle!.CanICallSomethingHereToHelp:)
var i:Int
for i = 1; i < numberOfSpaces; ++i{
operate(plus)
}
}
推荐答案
Swift 5或更高版本
在Swift 5中,我们可以使用新的Character属性 isWhitespace 和 isNewline
In Swift 5 we can use the new Character properties isWhitespace and isNewline
let str = "Hello, playground. Hello, playground !!!"
let spaceCount = str.reduce(0) { $1.isWhitespace && !$1.isNewline ? $0 + 1 : $0 }
print(spaceCount) // 4
如果您只想计算" "
let spaceCount = str.reduce(0) { $1 == " " ? $0 + 1 : $0 }
这篇关于在Swift中查找字符串中的空格数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文