bonjour, j'ai une fonction comme suit :
Le problème, c'est qu'elle ne fonctionne pas correctement.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 function Compare(t,s : string) : boolean; var a : boolean; i : integer; begin a := TRUE; i:=0; while (i<>length(s)) and a do begin inc(i); if (s[i]>='a') and (s[i]<='z') then begin if (ord(t[i])=ord(s[i])) or (ord(t[i])=ord(s[i])-32) then a:=TRUE else a:=FALSE; end; if (s[i]>='A') and (s[i]<='Z') then begin if (ord(t[i])=ord(s[i])) or (ord(t[i])=ord(s[i])+32) then a:=TRUE else a:=FALSE; end else begin if (t[i]=s[i]) then a:=TRUE else a:=FALSE; end; end; Compare:=a; end;
En fait, elle devrait regarder si deux mots (s et t) sont équivalents, à des majuscules près, mais ça ne marche que dans le cas où le mot "s" est entièrement en majuscule.
J'ai trouvé que c'était dû au "else" car, si je l'enlève et que je regarde deux mots entièrement formés de lettres ('a'..'z' ou 'A'..'Z'), il fonctionne correctement.
Ce qu'il y a c'est que je ne comprends pas pourquoi ça fait ça ! Donc si vous pouviez m'expliquer, ce serait sympa.
Si de plus vous pouviez me dire comment y remédier de façon "élegante", ce serait encore mieux. (en fait je vois bien une solution qui consisterait à ramener la fonction "principale" à un simple if/else, mais c'est loin d'être élégant : ça donnerait un truc du genre) :
Donc si vous voyez comment faire, tout en conservant une forme proche de ma première fonction, je préfèrerais !
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14 if ( (s[i]>='a') and (s[i]<='z') ) or ( (s[i]>='A') and (s[i]<='Z') ) then begin if (s[i]>='a') and (s[i]<='z') then begin if (ord(t[i])=ord(s[i])) or (ord(t[i])=ord(s[i])-32) then ... else ...; end else if (s[i]>='A') and (s[i]<='Z') then begin if (ord(t[i])=ord(s[i])) or (ord(t[i])=ord(s[i])+32)) then ... else ...; end; end else begin ... end;
Partager