Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!comp.vuw.ac.nz!canterbury!phys169 From: phys169@csc.canterbury.ac.nz Newsgroups: comp.lang.pascal Subject: Re: case (string) of Message-ID: <1991Jun6.112601.968@csc.canterbury.ac.nz> Date: 6 Jun 91 11:26:01 +1200 References: <1991Jun3.222059.16125@javelin.sim.es.com> <1991Jun4.012145.8522@ncsu.edu> Organization: University of Canterbury, Christchurch, New Zealand Lines: 56 In article <1991Jun4.012145.8522@ncsu.edu>, eagle@garfield.catt.ncsu.edu (Daniel L'Hommedieu) writes: > tpehrson@javelin.sim.es.com (Tim Clinkenpeel) writes: >>so i can't use case for strings, eh? what are my alternatives? a list of >>if-thens? (tp5.0) > > I liked to use a single string of all of the possibilities, evenly > spaced. You can use variable-length fields, separated by a delimiter, e.g. const Possible : string = 'CLARKSON,3COM,SNEAKER'; case pos(Net+',',Possible) of 1 : DoClarksonStuff; 10 : Do3ComStuff; 15 : DoSneakerStuff; else writeln('Invalid! Choose from: ',Possible); end {of case}; You have to be careful with counting, though. I wish Pascal allowed such case statements. I think TP3 did (Can anyone confirm this?). I used to think the reason was it generated code to index an array of labels (which would be very fast), but at least Turbo Pascal 5 doesn't - it does a series of tests, which would adapt well to strings, surely. By the way, be careful with... > possible="DIR CLS SET MATCH"; > { notice that all are 5 wide! } > test="SET"; > found=(pos(test,possible)/5); > if (found<>0) then > case found of > 1: begin /*perform stuff for DIR here*/ end; > 2: begin /*perform stuff for CLS here*/ end; because (a) you really need something like: possible:=' DIR CLS SET etc' notice the leading spaces.......^ or you need: found:=(pos(test,possible)+4) div 5); (b) watch out for small words being found in larger words earlier in the list, e.g. if you have 'RESET' and 'SET' as valid options, you must make sure 'SET' comes first in the list! (c) the method doesn't do a good job of spotting invalid input, where the input happens to be a substring of a valid alternative; that could be an advantage if you want to allow abbreviations, of course, but you may prefer a series of IF-THEN-ELSE tests, or writing a function that looks up a list. That would be required in any case if your list is larger than 255 bytes. What you choose then depends on the type of application - e.g. if you know the word is definately in a certain list one method may be more efficient; if all options in the list are unique within their first 3 letters another may be better. You could argue that the Pascal language is doing us a favour in requiring the programmer to choose the method, rather than have the compiler always choose. Hope this helps, Mark Aitchison, Physics, University of Canterbury, New Zealand.