英文:
Count certain character in a String
问题
你好,可以使用Swift来计算字符串中有多少个字符。例如,如果有以下字符串:
"100,101,305,222"
你可以通过以下方式找出字符串中有多少个逗号:
let inputString = "100,101,305,222"
let commaCount = inputString.components(separatedBy: ",").count - 1
commaCount
变量将包含字符串中逗号的数量。在这个例子中,commaCount
的值将是3,因为有3个逗号在字符串中。
英文:
my question is if it is possible in Swift to count how many characters are located in a string.
For example I have the following string:
"100,101,305,222"
Now I want to know how many commas are in this string? Is it possible to find out in Swift?
答案1
得分: 1
- 根据您想要的字符进行筛选
- 计算它们
"100,101,305,222"
.filter { $0 == "," }
.count
这是与 [tag:Swift] 有关的内容,与 [tag:SwiftUI] 无关。
英文:
- Filter by the character you want
- Count them
"100,101,305,222"
.filter { $0 == "," }
.count
It is [tag:Swift]. Nothing to do with the [tag:SwiftUI]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论