计算文本框中特定字符后的字符数

时间:2014-07-04 22:47:19

标签: vb.net winforms validation

使用winforms / vb.net

我正在尝试计算特定字符“。”后“textbox3”中存在多少个字符。在文本框中。

的示例:

2adf = 0(不存在“。”)

2adf。 = 0

2adf.2 = 1

2adf.2a = 2

2adf.2af = 3

2adf.2afe = 4

我已经有一个功能来搜索是否有“。”

if (CountCharacter(TextBox3.Text, ".") = 1) then
    'a "." exists so count number of characters after "."

end if

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
    Next
    Return cnt
End Function

我不知道如何检查“。”后的计数。虽然

3 个答案:

答案 0 :(得分:3)

您可以使用string.IndexOf方法执行此任务

Sub Main
    Dim test = "2adf.2afe"
    Dim result = CountCharsAfter(test, "."c)
    Console.WriteLine(result)
End Sub

Public Function CountCharsAfter(input as string, charToSearch as Char) as Integer
    DIm pos = input.LastIndexOf(charToSearch)
    if pos = -1 then
       return 0
    else
        return input.Length - (pos + 1)
    End if
End Function

答案 1 :(得分:0)

试试这个

    Dim NoChar As Integer = CalculateChra("12adf.2afe", ".")

Private Function CalculateChra(ByVal V_String As String, ByVal LastChar As Char) As Integer

    Dim Start As String = Split(V_String, LastChar)(0) & "."
    Dim M As String = V_String.Substring(Start.Length)
    Return M.Length
End Function

答案 2 :(得分:0)

dim n,cnt as integer
n=0
cnt=0
   Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar = Chr(46) Then
                n = Len(TextBox1.Text)
            End If
            If n <> 0 Then
                cnt += 1
            End If
            MsgBox(" no.of charectors after '.' is/are : " & cnt - 1)
        End Sub