搜索某个字符的字符串

时间:2016-04-27 15:57:53

标签: vb.net winforms

我正在创建一个Windows Forms表单,要求用户输入部件号,例如“XY12345E678”。然后,使用if - 语句让程序搜索第7个位置,并根据该位置中的字符执行一些代码。在这种情况下,它将是“E”或“F”。

例如:

      Dim partNumber as String
      partNumber = textboxPartNumber.Text
      Dim seventhPosition as String
      seventhPosition = partNumber.Substring(7, 1)

      If seventhPosition *is an "E"*
      ''' Do some code '''
      ElseIf seventhPosition *is an "F"*
      ''' Do some code '''
      Else
      ''' Do some code '''

3 个答案:

答案 0 :(得分:1)

如果你发现自己写了很长的If...ElseIf... ElseIf...语句,那么你应该考虑改用Select Case,如下所示:

Dim partNumber As String = textboxPartNumber.Text

If partNumber.Length >= 7 Then
    Dim seventhPosition As String = partNumber.Substring(7, 1)
    Select Case seventhPosition
        Case "E"
            ' some code
        Case "F"
            ' some code
        Case Else
            ' it is not an "E" or "F"
    End Select

Else
    ' the part number is too short
End If

您实际上并不需要在案例条款中使用=,但如果您愿意,可以使用Case Is = "E"等。

答案 1 :(得分:0)

你可以试试这个......

         Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim partNumber As String
            partNumber = textboxPartNumber.Text
            Dim seventhPosition As String
            seventhPosition = partNumber.Substring(7, 1)

            If seventhPosition = "E" Then
                MsgBox(seventhPosition)

            ElseIf seventhPosition = "F" Then
                MsgBox(seventhPosition)
            Else
                MsgBox("others")
            End If 
        End Sub

答案 2 :(得分:0)

            Dim partNumber As String
            partNumber = textboxPartNumber.Text

            Dim seventhPosition As String
            seventhPosition = partNumber.Chars(7)

            If seventhPosition = "E" OrElse seventhPosition = "F" Then
                'Do something
            End If