vb.net 获取字符串中的字符数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29313322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get count of a character within string
提问by Nasredine Habouria
How do you count specific character occurrences in a string in VB.NET?
Like for example I have a string of:
你如何计算 VB.NET 中字符串中特定字符的出现次数?
例如,我有一个字符串:
123#17453#40110#065
123#17453#40110#065
I would like to determine what is the code of getting the count of #sign
which is 3.
我想确定获取#符号计数的代码是什么3。
回答by OneFineDay
Here is a lambda expression:
这是一个 lambda 表达式:
Dim s As String = "123#17453#40110#065"
Dim result = s.Where(Function(c) c = "#"c).Count
回答by Craig Johnson
Try this:
尝试这个:
Dim count = "123.0#17453#40110#065".Count(Function(x) x = "#")
Or via an extension method placed in a module:
或者通过放置在模块中的扩展方法:
<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)
回答by Dai
Verbose VB.NET example:
详细的 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)
Obligatory minimalistic C# example:
强制性简约 C# 示例:
Int32 count = "123#17453#40110#065".Count( c => c == '#' );

