Nasredine Habouria
Nasredine Habouria

Reputation: 45

Get count of a character within string

How do you count specific character occurrences in a string in VB.NET?
Like for example I have a string of:

123#17453#40110#065

I would like to determine what is the code of getting the count of # sign which is 3.

Upvotes: 0

Views: 9786

Answers (3)

Craig Johnson
Craig Johnson

Reputation: 754

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)

Upvotes: 1

OneFineDay
OneFineDay

Reputation: 9024

Here is a lambda expression:

 Dim s As String = "123#17453#40110#065"
 Dim result = s.Where(Function(c) c = "#"c).Count

Upvotes: 7

Dai
Dai

Reputation: 154995

Verbose VB.NET example:

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:

Int32 count = "123#17453#40110#065".Count( c => c == '#' );

Upvotes: 0

Related Questions