Microsoft KB Archive/192353

= How To Generate Random Strings =

Article ID: 192353

Article Last Modified on 7/1/2004

-

APPLIES TO


 * Microsoft Visual FoxPro 3.0 Standard Edition
 * Microsoft Visual FoxPro 3.0b Standard Edition
 * Microsoft Visual FoxPro 5.0 Standard Edition
 * Microsoft Visual FoxPro 5.0a
 * Microsoft Visual FoxPro 6.0 Professional Edition
 * Microsoft FoxPro 2.6 for SCO/UNIX
 * Microsoft FoxPro 2.6 for MS-DOS
 * Microsoft FoxPro 2.6a Standard Edition
 * Microsoft FoxPro 2.6 Standard Edition
 * Microsoft FoxPro 2.6a Standard Edition
 * Microsoft Visual FoxPro 3.0b for Macintosh
 * Microsoft FoxPro 2.6a Professional Edition for Macintosh

-



This article was previously published under Q192353



SUMMARY
When testing SQL functions or creating test data, it is useful to be able to generate random string data. The FoxPro function SYS(2015) creates ten character random strings for use as procedure names. However, SYS(2015) does not allow the developer to specify a range of ASCII characters to use, nor does it allow the developer to specify the length of the string. This article demonstrates how to create and use the RandomString function.



MORE INFORMATION
Save the following code to a program file and run it. The WAIT WINDOW command displays a new random string each time a key is pressed. Press the ESC key to end the program. *-- Code begins here. SET TALK OFF ON ESCAPE CANCEL DO WHILE .T. && Press the escape key to quit WAIT WINDOW RandomString(65,122,1,15) ENDDO SET TALK ON

*--  *-- Function:   RandomString *-- Summary:   Generates a string of random characters *-- Usage:     RandomString(nLboundAscii, nUboundAscii,   *--               nLBoundLength, nUBoundLength) *-- Parameters: nLBoundAscii - Lowest ASCII value to use. *--            nUBoundAscii - Highest ASCII value to use. *--            nLBoundLength - Shortest string to generate. *--            nUBoundLength - Longest string to generate. *-- Example:   lsReturn = RandomString(65,122,1,15) *--  FUNCTION RandomString PARAMETERS liLowerBAscii, liUpperBAscii, ; liLowerBLength, liUpperBLength

*-- Initialize variables. lsString = "" liLength = 0 liCounter = 0

*-- Check for valid parameters and correct if needed. IF liLowerBAscii < 0 liLowerBAscii = 0 ENDIF IF liLowerBAscii > 255 liLowerBAscii = 255 ENDIF IF liUpperBAscii < 0 liUpperBAscii = 0 ENDIF IF liUpperBAscii > 255 liUpperBAscii = 255 ENDIF IF liLowerBLength < 0 liLowerBLength = 0 ENDIF liLength = INT((liUpperBLength - liLowerBLength + 1) ;    * RAND(-1) + liLowerBLength)

FOR liCounter = 1 TO liLength lsString = lsString + CHR(INT((        liUpperBAscii - liLowerBAscii + 1) ; * RAND + liLowerBAscii)) ENDFOR RETURN lsString *-- Code ends here.

