计算字符串中特定字符的数量。

huangapple go评论62阅读模式
英文:

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

  1. 根据您想要的字符进行筛选
  2. 计算它们
"100,101,305,222"    
    .filter { $0 == "," }
    .count

这是与 [tag:Swift] 有关的内容,与 [tag:SwiftUI] 无关。

英文:
  1. Filter by the character you want
  2. Count them
"100,101,305,222"    
    .filter { $0 == "," }
    .count

It is [tag:Swift]. Nothing to do with the [tag:SwiftUI]

huangapple
  • 本文由 发表于 2023年3月8日 17:44:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定