How to count the white spaces in a string in Swift

1 Answer

0 votes
func countWhitespaceCharacters(_ str: String) -> Int {
    var count = 0
    
    for ch in str {
        if ch.isWhitespace {
            count += 1
        }
    }
    
    return count
}

let str = "Swift \n  Programming \r Language \t "

print("Total white spaces: \(countWhitespaceCharacters(str))")



/*
run:
   
Total white spaces: 10

*/
 

 



answered Oct 20, 2024 by avibootz

Related questions

1 answer 123 views
1 answer 106 views
1 answer 89 views
1 answer 106 views
1 answer 78 views
...