Mega Code Archive

 
Categories / Delphi / Strings
 

Using strings in case statement

Title: Using strings in case statement Question: How can I use strings in a case statement? Answer: Unfortunally the case statement is limited to ordinal types, so you can not use it with strings. The idea is to find a way to "convert" the strings to compare in to a ordinal type. The simpliest way is to think of the strings as an array of string, and the ordinal representation of a string in this array is its index. Delphi gives us the "open array" parameter type for submitting a unknown number of parameters to a function. Lets use it to retrieve the position of a string in an array of string: function CaseString (const s: string; const x: array of string): Integer; var i: Integer; begin Result:= -1; // Default return parameter for i:= Low (x) to High (x) do begin if s = x[i] then begin Result:= i; Exit; end; end; end; Low() gives us the first array member (in most cases 0) and High() returns the last member. All we now have to do is to look for our searchstring in a for loop. Looks quite simple, hu? 8-) The function returns the position of the string s in the array of strings x. This position can be used in the case statement: search:= 'delphi3000'; case CaseString (search, ['delphi3000', 'delphipages', 'Torry's']) of 0: s:= 'Excellent!'; 1: s:= 'Good source'; 2: s:= 'Not bad!'; end; Update (08. June 2000): I have made some extensions to the CaseString function to search case insensitive and to look if the searchstring is in the compared string (Pos). function CaseString (const s: string; // Search for ci: Boolean; // if true looking case insensitive p: Boolean; // if true looking if s is in the compared string const x: array of string): Integer; var i: Integer; s1, s2: string; begin Result:= -1; for i:= Low (x) to High (x) do begin s1:= s; s2:= x[i]; if ci then begin AnsiUpperCase(s1); AnsiUpperCase(s2); end; if p then begin if Pos (s1, s2) 0 then begin Result:= i; Exit; end; end else begin if s1 = s2 then begin Result:= i; Exit; end; end; end; end;