Is there a function in c# that returns x times of given char or string. Or I must code it?
Thank you
Saanvi sharma
Unfortunately there's not a function that drives traffic to your crappy website either!
Below you will find a very brute force way or measuring this:
Private Function CountChar(ByVal c As Char, ByVal sSource As String, ByVal bCaseSensitive As Boolean) As Integer
Try
If Not bCaseSensitive Then
sSource = sSource.ToLower
c = Char.ToLower(c)
End If
Dim istart As Integer = InStr(sSource, c)
Dim istop As Integer = InStrRev(sSource, c)
Dim count As Integer = 0
For i = istart To istop
'add 1 for index
If sSource.Contains(c) Then count += 1
If sSource(i) = c Then
count += 1
End If
Next
Return count
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error!")
Return 0
End Try
End Function
You will call the code like so:
iCount = CountChar("a"c, sMyString, True)
This will return the number of lower case a's in the string sMyString.
Below you will find a very brute force way or measuring this:
int CountChars(char cChar, string sString, bool bCaseSensitive)
{
if (!bCaseSensitive)
{
cChar = Char.ToLower(cChar);
sString = sString.ToLower();
}
if (sString.IndexOf(cChar) == -1)
{
return 0;
}
else
{
int i;
int iCount = 0;
int iStart = sString.IndexOf(cChar);
for (i = iStart; iStart == sString.Length - 1; iStart++)
{
if (sString[i] == cChar)
{
iCount++;
}
}
return iCount;
}
}
You can chose to tell the function to check for case sensitivity or not.
EDIT Once I posted this code, I saw it was the C# forum. I have fixed the code.
The function you're asking for may well be Regex's class:
Imports System.Text.RegularExpressions
Public Class SearchCharOrString
Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Try
Dim cnt As Int32 = countCharOrString(
tbSearch.Text, tbIn.Text, chkSens.Checked)
lblCount.Text = "Count: " + cnt.ToString
Catch ex As Exception
End Try
End Sub
Function countCharOrString(search As String, inString As String, bCaseSensitive As Boolean)
Dim re As Regex = Nothing
If bCaseSensitive Then
re = New Regex(Regex.Escape(search))
Else
re = New Regex(Regex.Escape(search), RegexOptions.IgnoreCase)
End If
Dim count As Int32 = re.Matches(inString).Count
Return count
End Function
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.