在Swift中我该调用什么方法来查找字符串中的空格数?我想遍历该数字,如下所示:
@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
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 }