Contar ocurrencias de caracteres específicos en cadena
¿Cuál es la forma más sencilla de contar el número de ocurrencias de un carácter específico en una cadena?
Es decir, necesito escribir una función countTheCharacters () para que
str="the little red hen"
count=countTheCharacters(str,"e") 'count should equal 4
count=countTheCharacters(str,"t") 'count should equal 3
26 answers
Lo más sencillo es simplemente recorrer los caracteres de la cadena:
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
Uso:
count = CountCharacter(str, "e"C)
Otro enfoque que es casi tan efectivo y da código más corto es usar métodos de extensión 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:23:18
Esta es la manera sencilla
text="the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-06 17:29:16
Puedes probar esto
Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-11 17:19:09
Aquí hay una versión simple.
text.count(function(x) x = "a")
Lo anterior le daría el número de a en la cadena. Si quieres ignorar el caso:
text.count(function(x) Ucase(x) = "A")
O si solo quisieras contar letras:
text.count(function(x) Char.IsLetter(x) = True)
¡Inténtalo!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-21 21:36:50
O (en 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:25:30
Conversión del código de Ujjwal Manandhar a VB.NET como sigue...
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())
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:27:51
Gracias, @ guffa . La capacidad de hacerlo en una línea, o incluso dentro de una declaración más larga en.NET es muy útil. Esto VB.NET ejemplo cuenta el número de caracteres de LineFeed:
Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)
J devuelve el número de saltos de línea en myString.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:11
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-09 16:14:00
Cuando encontré esta solución estaba buscando algo ligeramente diferente ya que la cadena que quería contar era más larga que un carácter, así que se me ocurrió esta solución:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-09 16:47:58
Usando Expresiones Regulares...
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-19 15:53:45
Creo que esto sería lo más fácil:
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Return len(value) - len(replace(value, ch, ""))
End Function
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-15 19:45:12
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
Uso del código:
Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")
También puedes tenerlo como una extensión:
<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
Uso del código:
Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:29:15
Te sugiero que hagas esto:
String.Replace("e", "").Count
String.Replace("t", "").Count
También puede usar .Split("e").Count - 1
o .Split("t").Count - 1
respetivelly, pero da valores incorrectos si, por ejemplo, tiene una e o una t al comienzo de String
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-05 21:56:01
eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-25 01:39:58
Otra posibilidad es trabajar con Split:
Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:23:38
Encontré la mejor respuesta :P:
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-07 21:19:30
'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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-08 02:36:27
var charCount = "string with periods...".Count(x => '.' == x);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-23 01:26:21
Utilizo la siguiente función. No es la memoria más eficiente, pero es muy simple de entender, admite múltiples métodos de comparación, es solo 4 líneas, es rápido, principalmente funciona en VBA también, encontrará no solo caracteres individuales sino cualquier cadena de búsqueda (a menudo busco vbCrLf (s)).
Lo único que falta es la capacidad de iniciar la búsqueda desde un "Inicio"diferente
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
Una cosa que me gusta es que es compacto usar ejemplo.
str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3
Mientras estoy aquí, me gustaría to shill my inStB function, que, en lugar de devolver un recuento de una cadena, simplemente devolverá un booleano si la cadena de búsqueda está presente. Necesito esta función a menudo y esto hace que mi código sea más limpio.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-12 13:03:41
Otra posibilidad es usar una expresión regular:
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());
Por favor, convierta esto en VB.NET.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:24:37
Uso LINQ, y la solución es muy simple:
Código en C#:
count = yourString.ToCharArray().Count(c => c == 'e');
El código en una función:
public static int countTheCharacters(string str, char charToCount){
return str.ToCharArray().Count(c => c == charToCount);
}
Llame a la función:
count = countTheCharacters(yourString, 'e');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:30:09
Uso:
Function fNbrStrInStr(strin As Variant, strToCount As String)
fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function
Usé strin
como variante para manejar texto muy largo. La división puede ser basada en cero o basada en uno para el extremo inferior dependiendo de la configuración del usuario, y restando asegura el recuento correcto.
No incluí una prueba para que strcount sea más largo que strin
para mantener el código conciso.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:49:41
Qué grandes códigos para algo tan simple:
En C#, cree un método de extensión y use LINQ.
public static int CountOccurences(this string s, char c)
{
return s.Count(t => t == c);
}
Uso:
int count = "toto is the best".CountOccurences('t');
Resultado: 4.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 18:29:09
Uso:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:31:49
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 10:56:17
Aquí está el código directo que resuelve el problema del 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))
Ahora, esta es una función útil para resolver el problema del 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
Ejemplo de uso de la función:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 17:27:15