Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to replace a random word in a string with a random word from an array of words using Pascal

1 Answer

0 votes
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

*)


 



answered 7 hours ago by avibootz

Related questions

1 answer 140 views
...