How to remove the last word from a string in Pascal

2 Answers

0 votes
program RemoveLastWord;

uses 
  SysUtils; // LastDelimiter

const
  InputStr = 'c# rust c c++ java pascal';

function RemoveLast(s: string): string;
var
  LastSpacePos: Integer;
begin
  LastSpacePos := LastDelimiter(' ', s);
  if LastSpacePos > 0 then
    RemoveLast := Copy(s, 1, LastSpacePos - 1)
  else
    RemoveLast := s;
end;

begin
  WriteLn(RemoveLast(InputStr));
end.



(*
run:

c# rust c c++ java

*)



answered Sep 24, 2025 by avibootz
0 votes
program RemoveLastWordProgram;

uses
  SysUtils;

function RemoveLastWord(const s: string): string;
var
  trimmed: string;
  posSpace: Integer;
begin
  trimmed := TrimRight(s);              // remove trailing spaces
  posSpace := LastDelimiter(' ', trimmed);

  if posSpace = 0 then
    RemoveLastWord := trimmed                   // no space found
  else
    RemoveLastWord := Copy(trimmed, 1, posSpace - 1);
end;

var
  s: string;

begin
  s := 'c c++ c# java python';
  Writeln('1. ', RemoveLastWord(s));

  s := '';
  Writeln('2. ', RemoveLastWord(s));

  s := 'c';
  Writeln('3. ', RemoveLastWord(s));

  s := 'c# java python ';
  Writeln('4. ', RemoveLastWord(s));

  s := '  ';
  Writeln('5. ', RemoveLastWord(s));
end.




(*
run:

1. c c++ c# java
2. 
3. c
4. c# java
5. 

*)

 



answered Mar 27 by avibootz
...