|
-
February 18th, 2000, 08:54 AM
#1
palindromes
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?
-
February 18th, 2000, 09:07 AM
#2
Re: palindromes
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
-
February 18th, 2000, 09:18 AM
#3
Re: palindromes
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
[email protected]
The best way to escape a problem, is to solve it.
-
February 18th, 2000, 09:24 AM
#4
Re: palindromes
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
-
February 18th, 2000, 09:40 AM
#5
Re: palindromes
...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
[email protected]
The best way to escape a problem, is to solve it.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|