2

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.

3
  • Your example of 'a line' looks more like three lines, to me. Maybe you should clarify what the input and what the expected output is. Commented Sep 20, 2011 at 20:01
  • 2
    Which version of delphi are you using? Commented Sep 20, 2011 at 20:08
  • 2
    You are talking about 'multidimensional arrays', but your example suggests that you are only interested in a single-dimensional array... Commented Sep 20, 2011 at 20:19

1 Answer 1

5
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;
Sign up to request clarification or add additional context in comments.

8 Comments

@David: That is why I just fixed it, even before you sent your comment!
This is really sad, especially compared to how you need only one line for an extremely portable solution in Python: 'Hello there*3'.split('*')
@noob: Then replace '&' by '*'.
BlaXpirit: what prevents you from writing a Python-like library with similar string functions? Syntax may be different, but the results and ease of use could be the same. Add also some of the OS X Foundation string functions, and you got something nice to work with. <g>
@noob: Why would you prefer it to be a procedure rather than a function?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.