Find number of spaces in a string in Swift

后端 未结 3 1034
抹茶落季
抹茶落季 2020-12-11 18:41

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: U         


        
相关标签:
3条回答
  • 2020-12-11 19:21

    Another way could be the implementation of the following function :

    func nbSpacesIn(_ word: String) -> Int {
    return String(word.unicodeScalars.filter({$0.value == 32})).count}
    
    0 讨论(0)
  • 2020-12-11 19:22
    let title = "A sample string to test with."
    let count = title.componentsSeparatedByString(" ").count - 1
    print(count) // 5
    
    0 讨论(0)
  • 2020-12-11 19:44

    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 }
    
    0 讨论(0)
提交回复
热议问题