RosettaCodeData/Task/String-matching/XPL0/string-matching.xpl0

43 lines
1.4 KiB
Plaintext

include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
func StrLen(A); \Return number of characters in a string
char A;
int I;
for I:= 0 to -1>>1-1 do
if A(I) = 0 then return I;
func StrFind(A, B); \Search for string B in string A
\Returns index of first occurrence of string B in A, or -1 if B is not found
char A, B; \strings to be compared
int LA, LB, I, J;
[LA:= StrLen(A);
LB:= StrLen(B);
for I:= 0 to LA-LB do
[for J:= 0 to LB-1 do
if B(J) # A(J+I) then J:= LB+1;
if J = LB then return I; \found
];
return -1;
];
char Str; int I, J;
[Str:= "pack my box with";
\ 0123456789012345
Text(0, if StrFind(Str, "pack") = 0 then "yes" else "no"); CrLf(0); \1.
Text(0, if StrFind(Str, "ack") = 0 then "yes" else "no"); CrLf(0);
I:= StrFind(Str, "x w");
Text(0, if I >= 0 then "yes" else "no"); \2.
Text(0, ", at offset "); IntOut(0, I); CrLf(0);
I:= 0; J:= 0; \offsets of space characters
loop [I:= StrFind(Str+J, " ");
if I < 0 then quit;
IntOut(0, I+J); ChOut(0, ^ );
J:= J+I+1;
];
CrLf(0);
Text(0, if StrFind(Str, "X w") >= 0 then "yes" else "no"); CrLf(0);
Text(0, if StrFind(Str, "with") = StrLen(Str)-StrLen("with") then "yes" else "no"); CrLf(0); \3.
Text(0, if StrFind(Str, "x w" ) = StrLen(Str)-StrLen("x w" ) then "yes" else "no"); CrLf(0);
]