headball
February 18th, 2000, 07:54 AM
I need to write a program that opens a text file from the hard drive and find all the pa;indromes and all the non-palindromes and count the number of palindromes. How can i do this?
|
Click to See Complete Forum and Search --> : palindromes headball February 18th, 2000, 07:54 AM I need to write a program that opens a text file from the hard drive and find all the pa;indromes and all the non-palindromes and count the number of palindromes. How can i do this? Chris Eastwood February 18th, 2000, 08:07 AM This code will tell you whether the passed string is a palindrome : private Function IsPalindrome(byval sString as string) Dim sLeft as string Dim sRight as string ' sLeft = Left$(sString, len(sString) / 2) sRight = Right$(sString, len(sString) / 2) ' IsPalindrome = (StrComp(sLeft, StrReverse(sRight), vbTextCompare) = 0) ' End Function eg. MsgBox IsPalinDrome("Edam I Made") ' returns true - Requires VB6 for the 'StrReverse' function (but you can always rewrite that in VB5). Chris Eastwood CodeGuru - the website for developers http://codeguru.developer.com/vb Cakkie February 18th, 2000, 08:18 AM Here's the vb5 version: public sub command1_click() dim fFile as integer dim palindromes as integer dim nonPalidromes as integer fFile = freefile open "palindromes.dat" for input as #ffile do while not(eof(ffile)) line input #ffile, strLine if IsPalindrome(strLine) then palindromes = palindromes + 1 else nonPalidromes = nonPalindromes + 1 end if loop close #ffile end sub public function IsPalindrome(strToCheck as string) as boolean tmpWord = "" for t=1 to len(strToCheck) tmpWord = mid(strToCheck,t,1) & tmpWord next t if tmpWord = strToCheck then IsPalindrome = true else IsPalindrome = false end if End Function Tom Cannaerts slisse@planetinternet.be The best way to escape a problem, is to solve it. Chris Eastwood February 18th, 2000, 08:24 AM I'd recommend that you change the code : If tmpWord = strToCheck then IsPalindrome = true else IsPalindrome = false End If - to the method I used - the above doesn't take into account case sensitivity, eg "Edam I Made" would not be reported as a palindrome. The StrComp command is very useful (and fast) for checking whether strings are equal regardless of case. Chris Eastwood CodeGuru - the website for developers http://codeguru.developer.com/vb Cakkie February 18th, 2000, 08:40 AM ...or you can just add 1 line in the function IsPalindrome. Place following line at the first line of the function: strToCheck = LCase(strToCheck) 'this will place the string in lowercase, so when doing the check, the case will always match Tom Cannaerts slisse@planetinternet.be The best way to escape a problem, is to solve it. codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |