﻿ How to generate a random string of a fixed length in cache | InterSystems
Question
· Oct 16, 2017

# How to generate a random string of a fixed length in cache

Discussion (4)1

Isn't it easier to use the built function StringMin, especially when its the code does exactly the same thing?

```USER>w \$length(##class(%PopulateUtils).StringMin(100,100))
100```

Source code:

```ClassMethod StringMin(
minlen As %Integer = 1,
maxlen As %Integer = 1) As %String [ ProcedureBlock = 1 ]
{
if maxlen '< minlen {
set len=\$\$\$PRand(maxlen-minlen+1)+minlen,
string=""
for i=1:1:len {
Set charn=\$s(\$\$\$PRand(2):\$\$\$PRand(26)+65,1:\$\$\$PRand(26)+97),
string=string_\$s(charn<123:\$c(charn),1:" ")
}
quit string
} else { quit "" }
}```

It depends on, how long this string should be, and what do you expect to see there.

The simplest way is just generating it with \$random.

```set string=""
set length=100
for i=1:1:length set string=string_\$char(\$random(26)+97)```

To many time later, anyway for keep reference

``````Set string = ""
Set length = 256
For i=1:1:length {
Set Up = \$random(2)
Set tNum = \$random(28)
If (tNum = 26) {
Set tChar = "-"
}elseif (tNum = 27) {
Set tChar = "_"
} Else {
If Up {
// Upper case range
Set tChar = \$CHAR(tNum+65)
} Else {
// Lower case range
Set tChar = \$CHAR(tNum+97)
}
}
Set string = string _ tChar
}``````