[VB.NET] การตรวจสอบคำ ประโยค วลีพาลินโดรม (Palindrome) ด้วย VB.NET
http://www.g2gnet.com/webboard/images/vbnet/palindrome.pngพาลินโดรม (Palindrome) คือคำ วลี จำนวน หรือลำดับที่สามารถอ่านจากหลังไปหน้าหรือหน้าไปหลังแล้วมีความหมายเหมือนกัน เช่น ยาย, นาน, กนก, นอน, รรรรรร (ระ รัน รอน), radar, madam หรือจำนวนตัวเลข เช่น 919 818 ... สำหรับโค้ดชุดนี้แอดมินได้เขียนให้เป็นตัวอย่างอยู่ 3 ชุด ประกอบไปด้วย ...
1. การใช้คำสั่งภายใน หรือฟังค์ชั่นที่ติดมาในตัวแปลภาษาในการเปรียบเทียบ
2. ใช้การทำซ้ำด้วย WHILE โดยทำการเปรียบเทียบจากตัวแรก กับตัวสุดท้าย จากนั้นก็เพิ่มค่าตำแหน่งชุดตัวอักษรต้นฉบับ และลดค่าตำแหน่งในส่วนที่นำมาเปรียบเทียบ เช่น radar โดยเอา r ตัวแรกกับตัวสุดท้ายมาเปรียบเทียบ จากนั้นก็เอาตัว a ตัวที่ 2 (เพิ่มตำแหน่ง) กับ a ตัวที่ 4 (ลดตำแหน่ง) มาเปรียบเทียบกัน
3. ใช้ลูป FOR โดยที่หารความยาวออกเป็น 2 ส่วน แล้วทำการเปรียบเทียบกัน เช่น ยาย โดยเอาตัวแรกและตัวสุดท้ายมาเปรียบเทียบกัน
อนึ่ง ... คุณต้องทำการ Debugger ทีละสเต็ป จึงจะเข้าใจกระบวนการขั้นตอนได้ชัดเจนขึ้นครับ
มาดูโค้ดกันเถอะ ...
Public Class frmPalindrome
'// Use build in function.
Private Function CheckPalindrome(ByVal strText As String) As Boolean
Dim str As String
'// Reverse characters and convert to Upper Case.
str = StrReverse(UCase(strText))
'// Compare Original VS Reverse.
If str.Equals(UCase(strText)) Then
Return True
Else
Return False
End If
End Function
'// Make own function with WHILE.
Private Function CheckPalindromeWhile(ByVal strText As String) As Boolean
Dim iCurr As Integer = 0
Dim iLength As Integer = strText.Length - 1
strText = UCase(strText)
'// Repetitive with WHILE.
While iCurr < iLength
'// Compare from front to back, then increase the position and decrease the position.
If strText(iCurr) <> strText(iLength) Then Return False
'//
iCurr += 1
iLength -= 1
End While
Return True
End Function
'// Make own function with FOR.
Private Function CheckPalindromeFor(ByVal strText As String) As Boolean
CheckPalindromeFor = True
strText = UCase(strText)
'// Separate words into two parts.
For i As Integer = 0 To strText.Length \ 2
'// Divided into two parts and compare.
If strText(i) <> strText(strText.Length - i - 1) Then Return False
Next
End Function
Private Sub frmPalindrome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Label2.Text = ""
txtWord.Text = "Sator Arepo Tenet Opera Rotas" '"radar"
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtWord.Text = ""
txtWord.Focus()
End Sub
Private Sub btnCheck_Click(sender As System.Object, e As System.EventArgs) Handles btnCheck.Click
If Trim(txtWord.TextLength) = 0 Or txtWord.Text.Trim = "" Then Return
'// 3 Methods.
If CheckPalindrome(txtWord.Text) Then
'If CheckPalindromeWhile(txtWord.Text) Then
'If CheckPalindromeFor(txtWord.Text) Then
Label2.Text = txtWord.Text + " is a Palindrome."
Else
Label2.Text = txtWord.Text + " is not a Palindrome."
End If
txtWord.Focus()
End Sub
End Class
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
ขอบคุณครับ
หน้า:
[1]