noob
noob

Reputation: 65

How do I split a string at a certain character?

How do I split a line of text (e.g., Hello there*3) into an array? Everything before the * needs to be added to the first element and everything after the * needs to be added to second. I'm sure this is possible. I need to recall this later on and the first and second items must have relation to each other

I'm using Delphi 7.

Upvotes: 2

Views: 906

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

type
  TStringPair = array[0..1] of string;

function SplitStrAtAmpersand(const Str: string): TStringPair;
var
  p: integer;
begin
  p := Pos('&', Str);
  if p = 0 then
    p := MaxInt - 1;      
  result[0] := Copy(Str, 1, p - 1);
  result[1] := Copy(Str, p + 1);
end;

or, if you aren't into magic,

function SplitStrAtAmpersand(const Str: string): TStringPair;
var
  p: integer;
begin
  p := Pos('&', Str);
  if p > 0 then
  begin
    result[0] := Copy(Str, 1, p - 1);
    result[1] := Copy(Str, p + 1);
  end
  else
  begin
    result[0] := Str;
    result[1] := '';
  end;
end;

If you, for some utterly strange and slightly bizarre reason, need a procedure and not a function, then do

procedure SplitStrAtAmpersand(const Str: string; out StringPair: TStringPair);
var
  p: integer;
begin
  p := Pos('&', Str);
  if p > 0 then
  begin
    StringPair[0] := Copy(Str, 1, p - 1);
    StringPair[1] := Copy(Str, p + 1);
  end
  else
  begin
    StringPair[0] := Str;
    StringPair[1] := '';
  end;
end;

Upvotes: 5

Related Questions