Mega Code Archive

 
Categories / Delphi / Strings
 

Using the CASE instruction with strings

Title: Using the CASE instruction with strings Question: How to use the CASE instruction construct with string type arguments. Answer: Case statement functionality with strings Sometimes you might want to use a "case" instruction with strings. The following construct will provide this capability: case Trunc((Pos('Sam ','Harry /John /Samuel/Bob /Sam /Bill ')+6)/7) of 0: MessageDlg('The name is not in the list!',...); 1: MessageDlg('The name is Harry!',...); 2: MessageDlg('The name is John!',...); 3: MessageDlg('The name is Samuel!',...); 4: MessageDlg('The name is Bob!',...); 5: MessageDlg('The name is Sam!',...); 6: MessageDlg('The name is Bill!',...); end; If the search string ("Sam " in this example) is not on the list of choices then the Trunc() function will return a 0. Otherwise, it will return the indexed position of the search string in the list of valid choices. There are a few key "rules" you must follow to successfully use this construct. First, each item in the list of choices in the second arguement of the Pos() function must be padded out with spaces to make them all the same length (6 characters in this example). Second, the search item in the first argument of the Pos() function must be padded out to the same length. Third, separate each choice with a special character ("/" in this example) that can't appear in the actual choices. This eliminates the chance of getting a false match due to a match on the end of one choice and the beginning of the next. Fourth, the first of the two constants ("6" in this example) must be equal to the size of each of the strings to match, and the second constant ("7" in this example) must be one more than the length of the choice strings. Note, this technique will only return a match if the search string exactly matches a given list choice. That is, "Sam " will match with "Sam " but not with "Samuel".