Domanda

I need to use a string variable multiple times for checking if workds are palindromes. I am using this code:

var
s:string;
back:string;
x,n:integer;
d:array[1..n] of string;
begin
read(n);
for i:=1 to n do begin
readln(s);
s:= Lowercase(s);
for x:=length(s) downto 1 do begin

back:=back + s[x];

if back=s then begin
writeln('It's a palindrome');
end;

But if my n is higher than 1 the variable 'back' will be the same as from the first loop, so it won't find any more palindromes. I know that for numbers zero is neutral so that's how i can reset it, but i don't know for string. If i use

back:=' ';

words won't be palindromes also because of the space i guess, it just doesn't work with this.

È stato utile?

Soluzione

back := '';

But you can check for palindrome in another way:

len := length(x);
is_palindrome := true;
for x := 1 to len do begin
    if s[x] <> s[len - x + 1]
    then is_palindrome := false; break; end;
end;

if is_palindrome
then begin
    writeln('It''s a palindrome');
end
else begin
    writeln('It''s not a palindrome');
end;

Altri suggerimenti

From your comment I make that ease of use is a criterium. If you happen to use Free Pascal, for ease try

uses StrUtils;

if ReverseString(s)=s then
   writeln('It''s a palindrome')
else
   writeln('It''s not a palindrome');
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top