如何计算VB.NET中字符串中特定字符的出现次数?
比如我有一个字符串:
123#17453#40110#065
我想确定获取#
符号计数的代码是什么
这是3
。
答案 0 :(得分:5)
这是一个lambda表达式:
Dim s As String = "123#17453#40110#065"
Dim result = s.Where(Function(c) c = "#"c).Count
答案 1 :(得分:1)
试试这个:
Dim count = "123.0#17453#40110#065".Count(Function(x) x = "#")
或通过放置在模块中的扩展方法:
<Extension> Public Function Occurs(target As String, character As Char) As Integer
Return target.Count(Function(c) c = character)
End Function
Dim count = "123.0#17453#40110#065".Occurs("#"c)
答案 2 :(得分:0)
详细的VB.NET示例:
Dim s As String = "123#17453#40110#065"
Dim count As Integer = 0
For Each c As Char In s
If c = "#" Then count = count + 1
Next
Console.WriteLine("'#' appears {0} times.", count)
强制性简约C#示例:
Int32 count = "123#17453#40110#065".Count( c => c == '#' );