In this post, here is the VB.Net code to count the occurrences of a particular string in a another given string .
Suppose there is a case where we may want to check whether the string contains particular substring or not. And we may want to count the occurrences of the substring, in that case you can use this method and if count =0, then it means the substring is not found.
Below are the 2 codes for the same method, you can use whatever you want.
Method 1 :
Method 2 :
for C#.Net code :
>>> C#.Net Code to Count occurrences of String in Another String
Suppose there is a case where we may want to check whether the string contains particular substring or not. And we may want to count the occurrences of the substring, in that case you can use this method and if count =0, then it means the substring is not found.
Below are the 2 codes for the same method, you can use whatever you want.
Method 1 :
'''
<summary>
''' Method to Count occurrences of String in Another String
''' </summary>
''' <param
name="inputString"></param>
''' <param
name="searchStr"></param>
''' <param
name="matchCase">True-MatchCase, False-IgnoreCase</param>
''' <returns></returns>
Public Function CountOfStrInStr(inputString As String, searchStr As String, matchCase As Boolean) As Integer
Dim count As Integer = 0, TempLenth As
Integer = 0
If Not matchCase Then
inputString = inputString.ToLower()
searchStr = searchStr.ToLower()
End If
'getting first occurance
TempLenth =
inputString.IndexOf(searchStr, TempLenth)
While TempLenth <> -1
'incrementing lenth after finding string
TempLenth
+= searchStr.Length
count
+= 1
'getting next occurances till loop runs
TempLenth = inputString.IndexOf(searchStr, TempLenth)
End While
Return count
End Function
Method 2 :
'''
<summary>
''' Method to Count occurrence in String in Another String
using Regex
''' </summary>
''' <param
name="inputString"></param>
''' <param
name="searchStr"></param>
''' <param
name="matchCase">True-MatchCase, False-IgnoreCase</param>
''' <returns>count of SubString found in string</returns>
''' <remarks>Namespace needed System.Text.RegularExpressions;</remarks>
Public Function
CountOfStrInStr(inputString As String, searchStr As String, MatchCase As Boolean) As Integer
Dim count As Integer = 0
If MatchCase Then
count =
Regex.Matches(inputString, searchStr).Count
Else
count =
Regex.Matches(inputString, searchStr, RegexOptions.IgnoreCase).Count
End If
Return count
End Function
for C#.Net code :
>>> C#.Net Code to Count occurrences of String in Another String
No comments:
Post a Comment
Thanks for your comments.
-Sameer