How to split a string on multiple multi‑character delimiters (and keep them) in Pascal

1 Answer

0 votes
program SplitKeepMultiDelims;

type
  PStringArray = ^TStringArray;
  TStringArray = array[1..100] of string;

var
  Parts: TStringArray;
  Count: Integer;

function IsDelimChar(C: Char; const Delims: string): Boolean;
var
  i: Integer;
begin
  IsDelimChar := False;
  for i := 1 to Length(Delims) do
    if Delims[i] = C then
    begin
      IsDelimChar := True;
      Exit;
    end;
end;

procedure SplitKeepMultiDelims(const S: string; const Delims: string;
                               var OutParts: TStringArray; var OutCount: Integer);
var
  i, start: Integer;
  C: Char;
begin
  OutCount := 0;
  i := 1;

  while i <= Length(S) do
  begin
    C := S[i];

    if IsDelimChar(C, Delims) then
    begin
      { Count repeated delimiter characters }
      start := i;
      while (i <= Length(S)) and (S[i] = C) do
        Inc(i);

      Inc(OutCount);
      OutParts[OutCount] := Copy(S, start, i - start);
    end
    else
    begin
      { Collect normal text until next delimiter }
      start := i;
      while (i <= Length(S)) and (not IsDelimChar(S[i], Delims)) do
        Inc(i);

      Inc(OutCount);
      OutParts[OutCount] := Copy(S, start, i - start);
    end;
  end;
end;

var
  S: string;
  Delims: string;
  i: Integer;

begin
  S := 'aa==bbb---cccc++++ddddd';
  Delims := '=-+';

  SplitKeepMultiDelims(S, Delims, Parts, Count);

  for i := 1 to Count do
    Write('[', Parts[i], '] ');
end.




(*
run:

[aa] [==] [bbb] [---] [cccc] [++++] [ddddd] 

*)

 



answered Mar 9 by avibootz

Related questions

...