Character count in a string

  • Thread starter Thread starter Kuups
  • Start date Start date
K

Kuups

Hi!

I have a question regarding the count if character within a string
like for example I have a string of

e.g.

123#123#

I would like to determine what is the code? of getting the # sign
which the answer is 2.


Hope you can help me on this.


Thanks and Regards..
 
If you're looking to count a specific character in a string, here it is:

public function charcount(byval s as string, byval c as string) as long
dim i as long
dim count as long

count = 0
i = instr(s, c)
do while i > 0
count = count, + 1
i = instr(i + 1, s, c)
loop
charcount = count
end function

The key to this is the second instr call. It starts at the character after
the found location and returns the offset of the next instance. If there
are no more instances, it returns 0.

Mike Ober.
 
I was thinking that maybe the split function would be a way to do it using
the character as the delimiter. But if the character was the first or last
character of the string the count would be off. But it was a thought...

dim tmp() as string
tmp=split(s,c)
dim count as int32 = tmp.length-1
 
Terry,

We had once a thread where everybody had given another method for this.
I said joking the split function to add even another one.

Than there became a discussion which one was the quickest.
I did a test in this newsgroup and some gave extra methods

To find a "char" the indexof("#"c) was in that the fastest. Finding a string
the "Instr" in a way as showed by Michael 2 times faster than any other
tested (I did not check that procedure so I assume that it is right).

For a char as asked here are these two faremost the fastest both made by Jay
where the do until loop was slightly faster than the for each.

\\\.
Public Function test5(ByVal input As String, ByVal _
delimiter As Char) As Integer 'Jay 1(char)
Dim count, index As Integer
index = input.IndexOf(delimiter)
Do Until index < 0
count += 1
index = input.IndexOf(delimiter, index + 1)
Loop
Return count
End Function
Public Shared Function test6(ByVal input As String, _
ByVal delimiter As Char) As Integer 'JayB 2(char)
Dim count As Integer
For Each ch As Char In input
If ch = delimiter Then
count += 1
End If
Next ch
Return count
End Function
///

(The split was together with regex use the slowest where you would think in
more than 100 times)

I hope this gives some ideas to Kuups as well when he read this.

Cor
 
Back
Top