>> ZG·Lingua >  >> Language Learning >> Language Testing and Assessment

How can you check vowel or consonent in vbnet?

```vb.net

Imports System.Text.RegularExpressions

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

Dim inputString As String = TextBox1.Text

Dim resultLabel As Label = Label1

If String.IsNullOrEmpty(inputString) Then

resultLabel.Text = "Please enter a character."

Return

End If

If inputString.Length > 1 Then

resultLabel.Text = "Please enter only one character."

Return

End If

Dim character As Char = inputString.ToUpper()

' Using regular expressions

If Regex.IsMatch(character, "[AEIOU]") Then

resultLabel.Text = "Vowel"

ElseIf Regex.IsMatch(character, "[BCDFGHJKLMNPQRSTVWXYZ]") Then

resultLabel.Text = "Consonant"

Else

resultLabel.Text = "Not a letter"

End If

' Using String.Contains()

' If "AEIOU".Contains(character) Then

' resultLabel.Text = "Vowel"

' ElseIf "BCDFGHJKLMNPQRSTVWXYZ".Contains(character) Then

' resultLabel.Text = "Consonant"

' Else

' resultLabel.Text = "Not a letter"

' End If

End Sub

End Class

```

Explanation:

1. Input Handling:

- The code first checks if the user has entered anything in the `TextBox1`. If not, it displays an error message.

- It also checks if the user has entered more than one character and displays an error message if necessary.

2. Character Conversion:

- The input character is converted to uppercase using `inputString.ToUpper()` for case-insensitive comparison.

3. Using Regular Expressions:

- The code uses `Regex.IsMatch()` to check if the character matches a regular expression pattern for vowels (`[AEIOU]`) or consonants (`[BCDFGHJKLMNPQRSTVWXYZ]`).

- If the character matches either pattern, the corresponding label is set accordingly. Otherwise, it is classified as "Not a letter".

4. Using String.Contains() (Optional):

- The commented section shows an alternative approach using `String.Contains()`. It checks if the character exists within the strings "AEIOU" or "BCDFGHJKLMNPQRSTVWXYZ" to determine if it's a vowel or consonant.

Note: This code assumes that the user will only enter one character. You may need to modify it if you want to handle multiple character inputs.

Copyright © www.zgghmh.com ZG·Lingua All rights reserved.