A r t i c l e s
Navigation

Note: This site is
a bit older, personal views
may have changed.

M a i n P a g e

D i r e c t o r y

CASE of STRING Ability


uses
  sysutils; // or CompactSysutils.pas, or pwstrutil.pas ;-)

function StrCase(s: string; list: array of string): integer;
var 
  i: integer;
begin
   Result:= -1;
   for i:=0 to Length(list)-1 do
   if CompareText(s, List[i]) = 0 then
   begin
     Result:= i;
     break;
   end;
end;
How to use the above trick?

case StrCase('John', ['Tim','Bob','Danny', 'John', 'Jimmy']) of
   0: writeln('This is Tim here') ;
   1: writeln('This is Bob here') ;
   2: writeln('This is Danny here') ;
   3: writeln('This is John here') ;
   4: writeln('This is Jimmy here') ;
end;
Note that the index starts at zero (0).
Why would this be useful?

Many times if then else statements become cluttered and disorganized when analyzing text. Pretend you were changing a config file NAME/VALUE pair but you wanted to screen/check incoming NAME/VALUE pairs and verify they were correct before changing the config file:

procedure SetConfig(const name, value: string);
const CONFIG_FILE = 'config.ini';

  procedure SetConfigVal(name, value: string);
  begin
    // pretend we are modifying a config data in a config file
    OpenConfig(CONFIG_FILE);
    ChangeConfig(CONFIG_FILE, name, value);
    CloseConfig(CONFIG_FILE);
  end

const 
  SETTING1 = 0;
  SETTING2 = 1;
  BUFFERING = 2;
  PATH = 3;
  TIMEOUT = 4
begin

  case StrCase(input, ['setting1', 'setting2', 'buffering', 'path', 'timeout']) of

     SETTING1: writeln('sorry, cannot change "setting1" in config file');

     SETTING2: writeln('sorry, cannot change "setting2" in config file');

     BUFFERING: 
       begin
         writeln('please wait.. changing "buffering" in config file');
         SetConfigVal('buffering', value);
       end;

     PATH: 
       begin
         writeln('please wait.. changing "path" in config file');
         SetConfigVal('path', value);
       end;

     TIMEOUT: 
       begin
         if inttostr(value) > 100 then
         begin
           writeln('sorry "timeout" cannot be greater than 100 seconds');
           exit;
         end;
         writeln('please wait.. changing "timeout" in config file);
         SetConfigVal('timeout', value);
       end;
  end;

end;

The equivalent IF THEN ELSE code would be cluttered and less organized.

About
This site is about programming and other things.
_ _ _