program ReplaceRandomWordProgram;
const
MaxWords = 64;
type
TStringArray = array[1..MaxWords] of string;
procedure SplitWords(const s: string; var words: TStringArray; var count: Integer);
var
i, start: Integer;
temp: string;
begin
count := 0;
temp := '';
for i := 1 to Length(s) do
begin
if s[i] = ' ' then
begin
if temp <> '' then
begin
Inc(count);
words[count] := temp;
temp := '';
end;
end
else
temp := temp + s[i];
end;
if temp <> '' then
begin
Inc(count);
words[count] := temp;
end;
end;
function JoinWords(const words: TStringArray; count: Integer): string;
var
i: Integer;
resultStr: string;
begin
resultStr := '';
for i := 1 to count do
begin
resultStr := resultStr + words[i];
if i < count then
resultStr := resultStr + ' ';
end;
JoinWords := resultStr;
end;
function ReplaceRandomWord(const s: string; const repl: TStringArray; replCount: Integer): string;
var
words: TStringArray;
wordCount: Integer;
idx, replIdx: Integer;
begin
SplitWords(s, words, wordCount);
if (wordCount = 0) or (replCount = 0) then
begin
ReplaceRandomWord := s;
Exit;
end;
idx := Random(wordCount) + 1; { random word index }
replIdx := Random(replCount) + 1; { random replacement }
words[idx] := repl[replIdx];
ReplaceRandomWord := JoinWords(words, wordCount);
end;
var
text: string;
replacements: TStringArray;
replCount: Integer;
resultStr: string;
begin
Randomize;
text := 'The quick brown fox jumps over the lazy dog';
replCount := 5;
replacements[1] := 'c#';
replacements[2] := 'c++';
replacements[3] := 'java';
replacements[4] := 'rust';
replacements[5] := 'python';
resultStr := ReplaceRandomWord(text, replacements, replCount);
Writeln(resultStr);
end.
(*
run:
The quick brown fox jumps c# the lazy dog
*)