如何计算文本中的空白区域,就像我们如何得到明智的字符数一样,我需要在文本中使用空格数,如果用一个例子进行解释会更有帮助。
答案 0 :(得分:2)
您可以使用componentsSeparatedBy
或filter
功能
let array = string.components(separatedBy:" ")
let spaceCount = array.count - 1
或
let spaceCount = string.characters.filter{$0 == " "}.count
答案 1 :(得分:2)
如果你想考虑其他空白字符(不仅是 space ),还要使用正则表达式:
let string = "How to get count of the empty space in text,Like how we get character count like wise i need empty space count in a text, It would be more helpful if explained with an example."
let regex = try! NSRegularExpression(pattern: "\\s")
let numberOfWhitespaceCharacters = regex.numberOfMatches(in: string, range: NSRange(location: 0, length: string.utf16.count))
正则表达式\\s
考虑 tab , cr , lf 和 space
答案 2 :(得分:1)
最简单的方法是做这样的事情:
<div class="row">
<div class="col-sm-4" style="background-image:url('.....')">
content......
</div>
这样做是从字符串中取出字符,过滤掉所有不是 space 的字符,然后计算剩余元素的数量。
答案 3 :(得分:1)
你可以尝试。
let string = "Whitespace count in a string swift"
let spaceCount = string.characters.filter{$0 == " "}.count