计算字符串中特定字符出现次数的最简单方法是什么?计算字符串中特定字符的出现次数
即我需要编写一个函数countTheCharacters(),使
str="the little red hen"
count=countTheCharacters(str,"e") 'count should equal 4
count=countTheCharacters(str,"t") 'count should equal 3
计算字符串中特定字符出现次数的最简单方法是什么?计算字符串中特定字符的出现次数
即我需要编写一个函数countTheCharacters(),使
str="the little red hen"
count=countTheCharacters(str,"e") 'count should equal 4
count=countTheCharacters(str,"t") 'count should equal 3
最直接的方式是简单地通过字符串中的字符循环:
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
我来这里寻找*最快*的方法,不一定是最优雅的一个。这很快,但通过使用“For i as Integer = 0 value.Length - 1”,而不是For Each循环,可以快10%左右。 – NightOwl888 2014-08-13 19:34:06
''Count'不是'String'的成员.' – Panzercrisis 2014-10-14 14:57:18
@Panzercrisis:Count计数方法是'IEnumerable
另一种可能性是与斯普利特的工作:
Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1
另一种可能性是使用正则表达式:
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这。
或(在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
这里是直接代码解决了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
-1抱歉,不仅仅是_very_冗长,[您正在使用'GOTO's!](http://www.u .arizona.edu /〜rubinson/copyright_violations/Go_To_Considered_Harmful.html) – Basic 2012-04-03 22:30:49
将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())
谢谢,我选择了这个版本。似乎也非常快。我实际上是在文本字符串中搜索CR和/或LF,以及频率,以便我可以调整GridView中文本框的大小和高度以支持输出。 – htm11h 2015-03-03 20:46:49
你可以试试这个
Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
用Len(testCharStr)和Ceil来分隔你的答案,以此来处理字符串的出现。 – 2013-02-11 10:17:25
这个方法的好处是,它使用非常基本的fx。没有LINQ,RegEx或其他额外的库。可以用各种语言轻松复制。 – 2016-03-08 22:13:27
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")
在Stack Overflow上,您可以使用编辑器中的{}按钮来格式化代码。这次我把它作为一个编辑。 – Flexo 2012-06-16 11:02:01
这是简单的方式
text="the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
如果起始字母或/和endletter是要计数的数字,那么这并不总是正确的数字 – Reman 2013-07-23 12:11:37
@Remonn它总是给我正确的数字。不计算开始/结束字母的唯一方法是将SplitStringOptions.RemoveEmptyEntries作为第二个参数传递给Split() – alldayremix 2013-09-06 17:46:03
这很简单,但它会创建一些甚至不用于任何内容的字符串。 – Guffa 2014-10-14 19:17:28
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
当我发现这个解决方案,我一直在寻找的东西,因为我想算字符串略有不同的是长于一个字符,所以我想出了这个解决方案:
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
我建议你这样做:
String.Replace("e", "").Count
String.Replace("t", "").Count
您还可以使用.Split("e").Count - 1
或.Split("t").Count - 1
respetivelly,但它给错误的价值观,如果你,比如有一个E或处的String
这个vb.net是什么?我没有安装visual studio,但dotnetfiddle.net和ideone.com报告“'count'不是'String'的成员。” – 2016-03-08 22:45:50
开始我找到了最好的答案:P:
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
使用正则表达式...
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
'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
我使用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');
我在下面发布了一些vb.net等价物。 – MattB 2014-07-21 21:38:00
使用:
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
这甚至不会编译。 – 2014-12-19 06:25:23
这是什么?它甚至不编译,即使使用'Explicit Off'和'Option Strict Off'。 – 2017-04-01 17:32:08
它是Basic的其他形式,如[Visual Basic 6.0](http://en.wikipedia.org/wiki/Visual_Basic#Timeline)或[VBScript](http://en.wikipedia.org/wiki/VBScript )?问题是关于[VB.NET](http://en.wikipedia.org/wiki/Visual_Basic_.NET)。 – 2017-04-01 17:39:30
我认为这将是最简单的:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return len(value) - len(replace(value, ch, ""))
End Function
下面是一个简单的版本。
text.count(function(x) x = "a")
上面会给你字符串中a的个数。如果你想忽略大小写:
text.count(function(x) Ucase(x) = "A")
或者,如果你只是想算字母:
text.count(function(x) Char.IsLetter(x) = True)
给它一个镜头!
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
看起来像你打算发布这[在这里](http://stackoverflow.com/questions/9969824/vb-net-need-text-box-to-only-accept-numbers),虽然你已经发布了一个[答案](http://stackoverflow.com/a/24908847/301857)那里。 – 2014-12-19 06:17:47
用途:
Function fNbrStrInStr(strin As Variant, strToCount As String)
fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function
我以前strin
的变种来处理很长的文本。根据用户设置,拆分可以是基于零的或基于一个的,并且减去它可以确保正确的计数。
为了保持代码的简洁,我没有包含对strcount的测试长于strin
。
eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length
什么巨大的代码这么简单的东西:
在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
var charCount = "string with periods...".Count(x => '.' == x);
谢谢,@guffa。在一行中执行,或者在.NET中执行更长的语句的能力非常方便。此VB.NET示例计算LineFeed字符的数量:
Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)
j返回MyString中LineFeeds的数量。
我使用以下函数。它不是最高效的内存,但它很容易理解,支持多种比较方法,只有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
最快的方法是不要使用字符串。如果你真的对速度感兴趣,你应该寻找其他的东西。 – habakuk 2016-02-19 10:13:19
@habakuk,OP可以用什么非字符串值代替“小红母鸡”? – 2016-03-08 22:10:43
@johnywhy使用StringBuilder。请参阅https://msdn.microsoft.com/de-de/library/system.text.stringbuilder%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-11 – habakuk 2016-03-09 21:43:53