How to remove a random word from a string in Pascal

1 Answer

0 votes
program RemoveRandomWord;

uses 
  Classes;

function RemoveRndWord(input: string): string;
var
  words: TStringList;
  count, randomIndex: Integer;
begin
  words := TStringList.Create;
  words.Delimiter := ' ';
  words.StrictDelimiter := True;
  words.DelimitedText := input; // Splitting the string properly

  count := words.Count;
  if count = 0 then
    Exit(input);

  randomIndex := Random(count); // Get a random index
  words.Delete(randomIndex); // Remove the word at that index

  RemoveRndWord := words.DelimitedText;
  words.Free; // Free memory to avoid leaks
end;

var
  str, result: string;
begin
  Randomize; // Seed random number generator
  str := 'I''m not clumsy The floor just hates me';
  
  result := RemoveRndWord(str);
  
  WriteLn(result);
end.




(*
run:

I'm not The floor just hates me

*)  

 



answered May 5, 2025 by avibootz
...