Скачиваний:
28
Добавлен:
02.05.2014
Размер:
2.73 Кб
Скачать
program findAndReplace;
const
Nmax = 10000;
type
MyString = array[0..Nmax-1] of char;
var
str: MyString;
oldsubstr: MyString;
newsubstr: MyString;

{ вспомогательные функции }
function getSubstring(str: MyString; first, last : integer) : MyString;
var
res : MyString;
i : integer;
begin
if ( ( first > last ) or ( last > length( str ) ) ) then begin
if first > last then begin
res := ''; write(' first position must be <= last position ');
end else begin
res := ''; write(' last position must be < length(str) ');
end;
end
else begin
for i := 0 to last - first do begin
res[i] := str[first + i];
end;
res[last - first + 1] := char(0);
end;
getSubstring := res;
end;

function concatenate( str1,str2: MyString ) : MyString;
var
res : MyString;
i,ls1,ls2 : integer;
begin
ls1 := length(str1);
ls2 := length(str2);
res := str1;
for i := 0 to ls2 - 1 do
res[ls1 + i] := str2[i];
concatenate := res;
end;

function equals(str1, str2 : MyString) : boolean;
var i: integer;
begin
if length(str1) <> length(str2) then begin
equals := false; exit;
end
else begin
for i := 0 to length(str1) - 1 do begin
if (str1[i] <> str2[i]) then begin
equals := false;
exit;
end;
end;
end;
equals := true;
end;
{ вспомогательные функции }

function replace( str, oldsubstr, newsubstr: MyString ): MyString;
var
i, osl, sl: integer;
resultat: MyString;
begin
resultat := '';
i := 0;
sl := length(str);
osl := length(oldsubstr);
if osl = 0 then begin writeln('Old Substring must have length > 0'); replace := str; exit; end;
while i <= sl - osl do begin
if equals( oldsubstr, getSubstring( str,i,i + osl - 1 ) ) then begin
resultat := concatenate(resultat,newsubstr);
i := i + osl;
end
else begin
resultat := concatenate(resultat, getSubstring(str,i,i));
i := i + 1;
end;
end;
if i < sl then begin resultat := concatenate(resultat,getSubstring(str,i,sl-1)); end;
replace := resultat;
end;

begin
Writeln('Find And Replace Algoritm.');
Write('String: '); Readln(str);
Write('Old Substring: '); Readln(oldsubstr);
Write('New Substring: '); Readln(newsubstr);
Write('Result: '); writeln( replace( str, oldsubstr, newsubstr ) );
Writeln('Press any key to continue...');
Readln;
end.