# Generate a string of X characters in length

Please take a moment to consider if this thread is worth bumping.

## Recommended Posts

I'm trying to work out the best way of generating a string of a variable length of a single characters (let's say an *).

So basically I want to pass a variable into a function and that function returns a string of that number of characters .

So if i passed in 10 my string would be "**********"

In some languages

`str="*" * 8`

would return "********", but not LSL.

Is the only way to loop around adding one character each time, or is there a more efficient way of dong this?

Thanks

Edited by Bones Outlander
##### Share on other sites

Loop is the most general way to do it. You could write a custom function that applies a given character X times, and that's about as convenient as you can get.

Depending on your specific use-case, you could also go the other way around and do llGetSubString("***************", 0, n); assuming you know the maximum length you'll need. This way would be more speedy and memory-efficient (since you're not creating a bunch of immediately-discarded strings).

Edited by Wulfie Reanimator
• 5
##### Share on other sites

If you need a Lot of the same character in a row, you can decompose the number of repetitions into its binary representation and construct the string by doubling and adding 1;

Ex, 245 = 0b1111.0101 =>

```string x = "X";
// 245  = 1 1 1 1 0 1 0 1
string x245 = x;    // 1
x245 = x245+x245+x; // 1
x245 = x245+x245+x; // 1
x245 = x245+x245+x; // 1
x245 = x245+x245;   // 0
x245 = x245+x245+x; // 1
x245 = x245+x245;   // 0
x245 = x245+x245+x; // 1```

Or in general:

```string rep_string(string s, integer reps)
{   integer rep_max = 1024; // a sane upper limit that is a power of 2.
string ret; // the return value.
do{
ret = ret+ret;
if(rep_max&reps) ret+= s;
}while(rep_max>>1); // I hope the spec says 1>>1 == 0; I didn't check.
return ret;
}```

(untested)

Edited by Quistess Alpha
forgot to return ret.
• 1