如何在 Swift 中计算字符串中前导空格的数量?

Con*_*sed -3 string whitespace count swift

我想知道字符串中前导空格的数量。

说,如果字符串是" Hello world ",结果应该是 2

谢谢

Swe*_*per 6

一种方法是使用prefix(while:), 并计算你得到了多少个字符:

yourString.prefix(while: { $0 == " " }).count
Run Code Online (Sandbox Code Playgroud)