HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Produce an array of strings from a single string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
producearraysinglefromstringsstring

Problem

I have a function that reads a string like this

(AnimalCount+HumanCount)


and the result of this function is an array of strings

[ "(" , "AnimalCount" , "+" , "HumanCount" , ")" ]


Now, I have done 2 functions in order to do this:

The first one to check if a given char is "special" from the input string

function Validate(Character: Char): Boolean;
begin
  Validate:= Character in [',' , '+' , '-' , '*' , '/' , '(' , ')' , '^' ,
                         '[' , ']' , '%' , '&' , '=' , '' , ' ' ,
                         '.' , ';' , ':'];
end;


The second one to separate the strings from the input:

function GetToken(Chain:String):ArrayofString;
Var NTokens,i,j:Integer;
begin
  NTokens:=0;
  SetLength(Result,0);
  For i := 1 to Length(Chain) do
    if Validate(Chain[i]) then
      begin
        Inc(NTokens);
        setlength(Result,NTokens+1);
        Result[NTokens]:=Chain[i];
        Inc(NTokens);
      end
    else
      begin
        If Length(Result)<NTokens+1 then
          begin
            setlength(Result,NTokens+1);
            Result[NTokens]:='';
          end;
        Result[NTokens]:=Result[NTokens]+Chain[i];
      end;    
end;


Additionally, I had to put this after type to make it work this way:

Arrayofstring = array of String;


This functions are working, but I wonder if there is any way to improve it even further. I am new to Delphi, so any help would be appreciated.

Solution

-
Validate is a misleading name for what the function does. It does not validate anything - rather it checks if the given character is one of a special set. So it should be named IsSpecial or IsTokenDelimiter.

-
Growing an array one entry at a time is quite a bit of overhead. There are some ways of mitigating this.

-
Consider creating a local variable like currentCharacter in which Chain[i] - this would make it a little bit easier to read.

Context

StackExchange Code Review Q#43347, answer score: 4

Revisions (0)

No revisions yet.