Palindrome detection: Difference between revisions

Replaced existing program with a more complete one which accepts UTF-8 strings and can detect inexact palindromes.
m (Renamed "reverse" as "reversed". Changed "proc" to "func".)
(Replaced existing program with a more complete one which accepts UTF-8 strings and can detect inexact palindromes.)
Line 3,106:
 
=={{header|Nim}}==
The following program detects if UTF-8 strings are exact palindromes. If "exact" is set to "false", it ignores the white spaces and the differences of letter case to detect inexact palindromes. Differences in punctuation are still relevant.
<lang nim>func reversed(s: string): string =
<lang nim>import unicode
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
 
func isPalindrome(s: string): bool =
s == reversed(s)
 
echofunc isPalindrome("FoobooF"rseq: seq[Rune])</lang>: bool =
## Return true if a sequence of runes is a palindrome.
for i in 1..(rseq.len shr 1):
if rseq[i - 1] != rseq[^i]:
return false
result = newString(s.len)true
 
 
func isPalindrome(sstr: string; exact = true): bool {.inline.} =
## Return true if a UTF-8 string is a palindrome.
## If "exact" is false, ignore white spaces and ignore case.
 
if exact:
result = str.toRunes.isPalindrome()
else:
var rseq: seq[Rune]
for rune in str.runes:
if not rune.isWhiteSpace:
rseq.add rune.toLower
result = rseq.isPalindrome()
 
 
when isMainModule:
 
proc check(s: string) =
var exact, inexact: bool
exact = s.isPalindrome()
if not exact:
inexact = s.isPalindrome(exact = false)
let txt = if exact: " is an exact palindrome."
elif inexact: " is an inexact palindrome."
else: " is not a palindrome."
echo '"', s, '"', txt
 
check "rotor"
check "été"
check "αννα"
check "salà las"
check "In girum imus nocte et consumimur igni"
check "Esope reste ici et se repose"
check "This is a palindrom"</lang>
 
{{out}}
<pre>"rotor" is an exact palindrome.
"été" is an exact palindrome.
"αννα" is an exact palindrome.
"salà las" is an inexact palindrome.
"In girum imus nocte et consumimur igni" is an inexact palindrome.
"Esope reste ici et se repose" is an inexact palindrome.
"This is a palindrom" is not a palindrome.</pre>
 
=={{header|Objeck}}==
Anonymous user