Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of spaces in a string in Swift

Tags:

string

ios

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)
    }
}
like image 535
modesitt Avatar asked Jun 23 '15 03:06

modesitt


3 Answers

Swift 5 or later

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

If your intent is to count " " only

let spaceCount = str.reduce(0) { $1 == " " ? $0 + 1 : $0 }
like image 85
Leo Dabus Avatar answered Nov 14 '22 20:11

Leo Dabus


let title = "A sample string to test with."
let count = title.componentsSeparatedByString(" ").count - 1
print(count) // 5
like image 40
justinpawela Avatar answered Nov 14 '22 21:11

justinpawela


Another way could be the implementation of the following function :

func nbSpacesIn(_ word: String) -> Int {
return String(word.unicodeScalars.filter({$0.value == 32})).count}
like image 21
XLE_22 Avatar answered Nov 14 '22 20:11

XLE_22