Solved

# count the number of times that a certain character appears in a string

Posted on 2005-04-14
Medium Priority
350 Views
I have a string and I want to count the number of times that a certain character appears in that string.

The particular character that I want to find is vbCrLf

thx,

-broke
0
Question by:brokeMyLegBiking
• 8
• 7
• 3
• +2

LVL 75

Expert Comment

ID: 13784247
You can do it using the same logic as in your other question:
http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21388228.html
0

LVL 4

Author Comment

ID: 13784271
I posted the other question in the wrong area :(

I need a VB.NET solution.

thx
0

LVL 35

Expert Comment

ID: 13784274
Function CountOccurrences(ByVal rsExp As String, _
ByVal rsStr As Object, Optional ByVal cs As Boolean = False) _
As Integer
' Returns the number of occurrences of rsExp (expression)
' Returns 0 of no occurrences found.
Dim pPos As Integer
Dim lPos As Integer
Dim nPos As Integer
Dim nFirst As Integer
Dim lCnt As Integer

Try
Dim i  As Short = IIf(cs, 1, 0)
pPos = 0 ' previous find
lPos = 0 ' return position of right char
nPos = 1 ' position of next right most char
nFirst = 1
lCnt = 0

' loop thru every char in string until we
' find the last occurrence
Do
lPos = InStr(nPos, rsStr, rsExp, i)
If lPos > 0 Then
nPos = lPos + 1
pPos = lPos
lCnt += 1
Else
Exit Do
End If
Loop

Return lCnt
Catch e As System.Exception
End Try
End Function
0

LVL 12

Expert Comment

ID: 13784297
I've not tested this, but maybe this would work:

Imports System.text.regularexpressions

and then this is the code to count:

Dim regTest As New Regex("\r\n")  ' same as cr lf
Dim testStr As String = "Hello" & vbCrLf & "world" & vbCrLf & "how are" & vbCr & "you"
'                                                                                                              ^
'                                                                                                         not a crlf

Dim matchesX As MatchCollection = regTest.Matches(testStr)
Dim count as integer = matchesX.Count
Msgbox count.ToString
0

LVL 75

Expert Comment

ID: 13784304
>>I need a VB.NET solution.<<

Here it is:
Private Function CountChars(Value as string, SearchChar as string)

Return Value.Length - Value.Replace(SearchChar, String.Empty).Length

End Function
0

LVL 12

Expert Comment

ID: 13784332
you can see in the test string that there are only 2 vbCrlLf  chars.... and the value for count is 2.
0

LVL 96

Expert Comment

ID: 13784354
Imports System.Text.RegularExpressions.

Public Class Regex_Library

Public Shared Function Occurs(ByVal inputText As String, ByVal findText As String, _
Optional ByVal findOptions As RegexOptions = RegexOptions.None) As Integer

Dim regexCounter As Regex = New Regex(inputText, findOptions)

Return regexCounter.Matches(findText).Count

End Function 'Occurs'

End Class 'Regex_Library'

Usage:

Dim crlfCount As Integer = Regex_Library.Occurs(<input text>, vbCrLf)

Bob
0

LVL 12

Assisted Solution

S-Twilley earned 400 total points
ID: 13784359
nice acperkins, but you need to divide by the length of the string your replacing:

Private Function CountChars(Value as string, SearchChar as string)
Dim lenDiff As Integer = Value.Length - Value.Replace(SearchChar, String.Empty).Length
lenDiff = lenDiff / SearchChar.Length
Return lenDiff
End Function

==============

vbCrLf  is a character pair as far as i know, so should have a length of 2
0

LVL 75

Accepted Solution

Anthony Perkins earned 800 total points
ID: 13784395
Oops, forgot to divide:

Private Function CountChars(Value as string, SearchChar as string) As Integer

Return Value.Length - Value.Replace(SearchChar, String.Empty).Length / SearchChar.Length

End Function
0

LVL 75

Expert Comment

ID: 13784430
Still wrong (maybe I shoud test my code <g>):

Private Function CountChars(ByVal Value As String, ByVal SearchChar As String) As Integer

Return CInt((Value.Length - Value.Replace(SearchChar, String.Empty).Length) / SearchChar.Length)

End Function
0

LVL 12

Expert Comment

ID: 13784453
I beat you to correcting yourself there :P...   clever though... and a nice alternative to using Regex
0

LVL 75

Expert Comment

ID: 13784455
>>nice acperkins<<
I was just porting the T-SQL solution offered the questioner earlier.  Using Regex with VB.NET is obviously a better solution.
0

LVL 12

Expert Comment

ID: 13784478
well ok then..

"nice for finding that one"
0

LVL 35

Expert Comment

ID: 13784489
actually that won't work for you. Here, I used this function before and it worked for me:

Public Function CountOccurrences(ByVal myString As String, ByVal searchFor As String, ByVal CaseSensitive As Boolean) As Integer
Dim iLen As Integer
Dim iCharLen As Integer
Dim iAns As Integer
Dim sInput As String
Dim sChar As String
Dim iCtr As Integer
Dim iEndOfLoop As Integer
Dim bytCompareType As Byte

sInput = myString
If sInput = "" Then Exit Function
iLen = Len(sInput)
iCharLen = Len(searchFor)
iEndOfLoop = (iLen - iCharLen) + 1
bytCompareType = IIf(CaseSensitive, vbBinaryCompare, _
vbTextCompare)

For iCtr = 1 To iEndOfLoop
sChar = Mid(sInput, iCtr, iCharLen)
If StrComp(sChar, searchFor, bytCompareType) = 0 Then _
iAns = iAns + 1
Next

CountOccurrences = iAns

End Function
0

LVL 75

Expert Comment

ID: 13784523
YZlat,

Perhaps I am stating the obvious, but is that not overkill, for such a simple task.  Or am I missing something?
0

LVL 12

Expert Comment

ID: 13784526
Which solution won't work YZlat?
0

LVL 35

Expert Comment

ID: 13784642
my previous one
0

LVL 4

Author Comment

ID: 13784712
acperkins solution is clever, and simple, and it works fine.

Because I have Option Strinct on, I had to add a Math.Floor:

lines = CInt(Math.Floor((fileOut.Length - fileOut.Replace(vbCrLf, String.Empty).Length) / 2))

works great, thanks all.

-Joe
0

LVL 12

Expert Comment

ID: 13784741
Ok... and just to make sure there's no confusion...

the regex sample I used is what i posted... the other sample I put up was acperkins sample, and i was just correcting a mistake / flaw (which acperkins then corrected anyway)... I don't want points shared incorrectly
0

LVL 12

Expert Comment

ID: 13784755
no worries, was a bit slow there, but all was ok!
0

LVL 75

Expert Comment

ID: 13784806
brokeMyLegBiking,

>>Because I have Option Strinct on, I had to add a Math.Floor:<<
So do I, but all I needed was CInt (I did not need Math.Floor).  Go figure.  Thanks for the points.

S-Twilley,
>>the regex sample I used is what i posted<<
I still prefer the regex solution <g>
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ruâ€¦
XML Literals are a great way to handle XML files and the community doesnâ€™t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with wâ€¦
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. â€¦
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can eâ€¦
###### Suggested Courses
Course of the Month14 days, 16 hours left to enroll