Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Multi Lingual BoolToStr() and SexToStr() Conversions

Title: Multi Lingual BoolToStr() and SexToStr() Conversions Question: Borland has IntToStr(),FloatToStr() etc. It would be nice to have other conversions such as Boolean and Sex. This article demonstrates how to implement this. The functions are useful to add to your "Little Black Box" but also serve to demonstrate to beginners how to use Enum types and constant arrays in loops. It is easy to expand them to add additional languages. Simply extend the TEnumLang type and add the language specific text to the Text arrays. Set MaxLang to the last type in list. Answer: type TSex = (sxMale,sxFemale); TEnumLang = (elGeneric,elEnglish,elAfrikaans); const BoolText : array [elGeneric..elAfrikaans,false..true] of string = (('FALSE','TRUE'), ('NO','YES'), ('NEE','JA') ); SexText : array [elGeneric..elAfrikaans,sxMale..sxFemale] of string = (('M','F'), ('MALE','FEMALE'), ('MANLIK','VROULIK') ); MaxLang = elAfrikaans; // Set to last enum if modified above function BoolToStr(BoolVal : boolean; Language : TEnumLang) : string; begin Result := BoolText[Language,Boolval]; end; function StrToBool(BoolStr : string) : boolean; var BStr : string; i : TEnumLang; ii, Retvar : boolean; begin Retvar := false; BStr := UpperCase(BoolStr); for i := elGeneric to MaxLang do begin for ii := false to true do begin if Uppercase(BoolText[i,ii]) = BStr then begin Retvar := ii; break; end; end; end; Result := Retvar; end; function SexToStr(Sex : TSex; Language : TEnumLang) : string; begin Result := SexText[Language,Sex]; end; function StrToSex(SexStr : string) : TSex; var SStr : string; i : TEnumLang; ii, Retvar : TSex; begin Retvar := sxMale; SStr := UpperCase(SexStr); for i := elGeneric to MaxLang do begin for ii := sxMale to sxFemale do begin if Uppercase(SexText[i,ii]) = SStr then begin Retvar := ii; break; end; end; end; Result := Retvar; end;