Подсчет вхождений определенных символов в строку - PullRequest
59 голосов
/ 04 марта 2011

Какой самый простой способ подсчитать количество вхождений определенного символа в строку?

То есть мне нужно написать функцию countTheCharacters (), чтобы

str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3

Ответы [ 26 ]

0 голосов
/ 20 февраля 2015

Использование:

Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

Я использовал strin как вариант для обработки очень длинного текста. Разделение может быть на основе нуля или на единицу для нижнего уровня в зависимости от пользовательских настроек, и вычитание обеспечивает правильное количество.

Я не включил тест для strcount, который длиннее strin для краткости кода.

0 голосов
/ 23 июля 2014
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
0 голосов
/ 27 июня 2011

Вот прямой код, который решает проблему ОП:

        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))

Теперь эта удобная функция для решения проблемы ОП:

    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
0 голосов
/ 26 февраля 2014

Использование:

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
0 голосов
/ 08 октября 2013
    ' 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
0 голосов
/ 08 января 2013

Я нашел лучший ответ: P:

String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...