开发者

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开发者_JAVA百科 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜