Search code examples
swiftstringcountwhitespace

How to count number of leading spaces in a string in Swift?


I want to know how to count the number of leading spaces in a string in Swift.

Say, if the string is " Hello world ", the result should be 2

Thanks


Solution

  • One way is to use prefix(while:), and count how many characters you got:

    yourString.prefix(while: { $0 == " " }).count