在这个问题上遇到困难时,似乎无法做到这一点。我在文本框中有一些文字。然后我使用组合下拉框选择可能出现在文本字段中的字母。然后,我需要显示所选字母出现在文本框中的次数。下面列出的是我的代码,我收到了一些错误。我得到的最大错误是
“索引和长度必须指向字符串中的位置。参数名称:长度”
我认为这与子字符串功能有关。我认为它必须对文本框中的字符长度做一些事情。任何有助于使其正常工作的帮助非常感谢,
Private Sub cboSelectText_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboSelectText.SelectedIndexChanged
'value to find
Dim strLetterToFind As String
'String to search
Dim strStringToSearch As String = txtWordsToScan.Text
'Current Character
Dim chrCurrentCharacter As Char
'Length of text
Dim intLengthOfText As Integer
intLengthOfText = strStringToSearch.Length
'Letter totals
'Dim intLoopCounter As Integer
'Count for the display
Dim intLetterA, intLetterE, intLetterI, intLetterO, intLetterU, intLetterCH, intWords As Integer
Select Case cboSelectText.SelectedIndex
Case 1
strLetterToFind = "A"
Case 2
strLetterToFind = "E"
Case 3
strLetterToFind = "I"
Case 4
strLetterToFind = "O"
Case 5
strLetterToFind = "U"
Case 6
strLetterToFind = "CH"
Case 7
strLetterToFind = " "
Case Else
strLetterToFind = String.Empty
End Select
For intLoopCounter As Integer = 0 To intLengthOfText
If chrCurrentCharacter = strStringToSearch.Substring(intLoopCounter, 1).ToUpper Then
If strLetterToFind = "A" Then
intLetterA += 1
lblANumberTotal.Text = CStr(intLetterA)
ElseIf chrCurrentCharacter = "E" Then
intLetterE += 1
lblENumberTotal.Text = CStr(intLetterE)
ElseIf chrCurrentCharacter = "I" Then
intLetterI += 1
lblINumberTotal.Text = CStr(intLetterI)
ElseIf chrCurrentCharacter = "O" Then
intLetterO += 1
lblONumberTotal.Text = CStr(intLetterO)
ElseIf chrCurrentCharacter = "U" Then
intLetterU += 1
lblUNumberTotal.Text = CStr(intLetterU)
ElseIf chrCurrentCharacter = "CH" Then
intLetterCH += 1
lblCHNumberTotal.Text = CStr(intLetterCH)
ElseIf chrCurrentCharacter = " " Then
intWords += 1
lblTotalNumberWords.Text = CStr(intWords)
End If
End If
Next
End Sub
答案 0 :(得分:1)
这应该做你要求的:
Dim strLetterToFind As String
strLetterToFind = ComboBox1.SelectedItem
Try
lblTotalNumberWords.Text = Regex.Matches(TextBox1.Text,Regex.Escape(strlettertofind)).Count.ToString)
Catch ex As Exception
lblTotalNumberWords.Text = "Please select a option in the combo box"
End Try
您需要导入System.Text.RegularExpressions才能正常工作。
如果您对此有任何问题,请告诉我