计算字符串中特定字符出现次数的最简单方法是什么?
也就是说,我需要编写一个函数countTheCharacters(),以便
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3
答案 0 :(得分:66)
最直接的是简单地遍历字符串中的字符:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then
cnt += 1
End If
Next
Return cnt
End Function
用法:
count = CountCharacter(str, "e"C)
另一种几乎同样有效并且代码更短的方法是使用LINQ扩展方法:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return value.Count(Function(c As Char) c = ch)
End Function
答案 1 :(得分:60)
这是一种简单的方法:
text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
答案 2 :(得分:31)
你可以试试这个
Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
答案 3 :(得分:14)
这是一个简单的版本。
text.count(function(x) x = "a")
上面会给你字符串中a的数量。如果你想忽略大小写:
text.count(function(x) Ucase(x) = "A")
或者如果你只想数字:
text.count(function(x) Char.IsLetter(x) = True)
试一试!
答案 4 :(得分:4)
谢谢,@guffa。能够在一行中,甚至在.NET中的更长语句中执行它是非常方便的。此VB.NET示例计算LineFeed字符的数量:
Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)
j返回MyString中的LineFeeds数。
答案 5 :(得分:4)
或(在VB.NET中):
Function InstanceCount(ByVal StringToSearch As String,
ByVal StringToFind As String) As Long
If Len(StringToFind) Then
InstanceCount = UBound(Split(StringToSearch, StringToFind))
End If
End Function
答案 6 :(得分:3)
将Ujjwal Manandhar的代码转换为VB.NET,如下所示......
Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())
答案 7 :(得分:2)
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
Dim iPos = -1
Dim iFound = 0
Do
iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
If iPos <> -1 Then
iFound += 1
End If<br/>
Loop Until iPos = -1
Return iFound
End Function
代码使用:
Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")
您也可以将其作为扩展名:
<Extension()> _
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
Dim iPos = -1
Dim iFound = 0
Do
iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
If iPos <> -1 Then
iFound += 1
End If
Loop Until iPos = -1
Return iFound
End Function
代码使用:
Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")
答案 8 :(得分:2)
Public Class VOWELS
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str1, s, c As String
Dim i, l As Integer
str1 = TextBox1.Text
l = Len(str1)
c = 0
i = 0
Dim intloopIndex As Integer
For intloopIndex = 1 To l
s = Mid(str1, intloopIndex, 1)
If (s = "A" Or s = "a" Or s = "E" Or s = "e" Or s = "I" Or s = "i" Or s = "O" Or s = "o" Or s = "U" Or s = "u") Then
c = c + 1
End If
Next
MsgBox("No of Vowels: " + c.ToString)
End Sub
End Class
答案 9 :(得分:2)
当我找到这个解决方案时,我正在寻找一些略有不同的东西,因为我想要计算的字符串长于一个字符,所以我提出了这个解决方案:
Public Shared Function StrCounter(str As String, CountStr As String) As Integer
Dim Ctr As Integer = 0
Dim Ptr As Integer = 1
While InStr(Ptr, str, CountStr) > 0
Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
Ctr += 1
End While
Return Ctr
End Function
答案 10 :(得分:2)
我认为这是最简单的:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return len(value) - len(replace(value, ch, ""))
End Function
答案 11 :(得分:2)
使用正则表达式......
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return (New System.Text.RegularExpressions.Regex(ch)).Matches(value).Count
End Function
答案 12 :(得分:1)
另一种可能性是使用Split:
Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1
答案 13 :(得分:1)
eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length
答案 14 :(得分:1)
我使用LINQ,解决方案非常简单:
C#中的代码:
count = yourString.ToCharArray().Count(c => c == 'e');
函数中的代码:
public static int countTheCharacters(string str, char charToCount){
return str.ToCharArray().Count(c => c == charToCount);
}
调用该函数:
count = countTheCharacters(yourString, 'e');
答案 15 :(得分:1)
我建议你这样做:
String.Replace("e", "").Count
String.Replace("t", "").Count
您也可以分别使用.Split("e").Count - 1
或.Split("t").Count - 1
,但如果您在String
的开头有e或t,则会提供错误的值。
答案 16 :(得分:0)
' Trying to find the amount of "." in the text
' if txtName looks like "hi...hi" then intdots will = 3
Dim test As String = txtName.Text
Dim intdots As Integer = 0
For i = 1 To test.Length
Dim inta As Integer = 0 + 1
Dim stra As String = test.Substring(inta)
If stra = "." Then
intdots = intdots + 1
End If
Next
txttest.text = intdots
答案 17 :(得分:0)
我找到了最好的答案:P:
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
答案 18 :(得分:0)
使用:
Function fNbrStrInStr(strin As Variant, strToCount As String)
fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function
我使用strin
作为变体来处理很长的文本。根据用户设置,拆分可以从零开始,也可以从一开始用于低端,并且减去它可以确保正确的计数。
我没有为strcount包含超过strin
的测试,以保持代码简洁。
答案 19 :(得分:0)
对于这么简单的事情有什么巨大的代码:
在C#中,创建一个扩展方法并使用LINQ。
public static int CountOccurences(this string s, char c)
{
return s.Count(t => t == c);
}
用法:
int count = "toto is the best".CountOccurences('t');
结果:4。
答案 20 :(得分:0)
var charCount = "string with periods...".Count(x => '.' == x);
答案 21 :(得分:0)
另一种可能性是使用正则表达式:
string a = "this is test";
string pattern = "t";
System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
MessageBox.Show(m.Count.ToString());
请将其转换为VB.NET。
答案 22 :(得分:0)
我使用以下功能。它不是最有效的内存但它理解起来非常简单,支持多种比较方法,只有4行,速度快,大多数也适用于VBA,不仅可以找到单个字符,还可以找到任何搜索字符串(我经常搜索VbCrLf) (一个或多个))。
唯一缺少的是能够从不同的“开始”
开始搜索 Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
Return UBound(Split(myInput, Search,, myCompareMethod))
End Function
我喜欢的一点是使用示例很紧凑。
str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3
当我在这里的时候,我想填充我的inStB函数,它不是返回字符串的计数,而是在搜索字符串存在时返回一个布尔值。我经常需要这个功能,这使我的代码更清晰。
Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
Return False
End Function
答案 23 :(得分:-2)
使用:
Dim a
inputString = InputBox("Enter String", "Enter Value", "")
MyString = UCase(inputString)
MsgBox MyString
Dim stringLength
stringLength = Len(MyString)
Dim temp
output = ""
i = 1
Do
temp = Mid(MyString, i, 1)
MsgBox temp & i
CharacterCount = len(MyString) - len(Replace(MyString, temp, ""))
MyString = Replace(MyString, temp, "")
output = output & temp & ": " & CharacterCount & vbNewline
Loop While MyString <> ""
MsgBox output
答案 24 :(得分:-3)
Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) And Not e.KeyChar = "." Then
e.Handled = True
Else
If e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0 Then
e.Handled = True
End If
End If
End Sub
答案 25 :(得分:-8)
以下是解决OP问题的直接代码:
Dim str As String = "the little red hen"
Dim total As Int32
Dim Target As String = "e"
Dim Temp As Int32
Dim Temp2 As Int32 = -1
Line50:
Temp = str.IndexOf(Target, Temp2 + 1)
Temp2 = Temp
If Temp <> -1 Then
' Means there is a target there
total = total + 1
GoTo Line50
End If
MessageBox.Show(CStr(total))
现在,这是解决OP问题的一个方便的功能:
Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
Dim total As Int32
Dim Temp As Int32
Dim Temp2 As Int32 = -1
Line50:
Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
Temp2 = Temp
If Temp <> -1 Then
' Means there is a target there
total = total + 1
GoTo Line50
Else
Return total
End If
End Function
使用该功能的例子:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = "the little red hen"
MessageBox.Show(CStr(CountOccurrence(str, "e")))
' It will return 4
End Sub