Creating C # strings by number of characters

Is there a way to generate a 250 underscore string without using a loop? I want to avoid writing code like this:

var myString= '';
for (var i=0; i < 250; i++) {
    myString += '_';
}

      

+2


source to share


5 answers


There is no built-in solution, but the Repeat String question - Javascript has a good solution:

If you don't want to change the String prototype, you can simply do:



var num = 250;
var myChar = '_';
var myString = new Array(num + 1).join(myChar);

      

This creates an array of 251 undefineds and then concatenates them with your character. Since undefined is '' (empty string) when converted to string in .join()

, this gives you the string you are after.

+8


source


A bit of a hack, but you could do something like:



var arr = new Array(251);
var lineStr = arr.toString().replace(/,/g, "_");

      

+2


source


Use a constant that is longer than the longest number of underscores and use substring()

to get as many as you need.

+1


source


var myString = "__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________";

      

Why do you want to generate it? And why do you want to avoid the loop for

?

0


source


Here's a function that creates a string in (more or less) logarithmic runtime:

function repeat(string, times) {
    if(!(times = +times)) return ''; // convert to number; check for NaN, 0
    var result = '' + string, i = 1;
    for(; i * 2 <= times; i *= 2) result += result;
    for(; i < times; ++i) result += string;
    return result;
}

var u250 = repeat('_', 250);

      

I hope I haven't messed up the loop conditions;)

In addition, Aaron's offer can be automated:

function underscores(count) {
    while(count > underscores.buffer.length)
        underscores.buffer += underscores.buffer;
    return underscores.buffer.substring(0, count);
}
underscores.buffer = '_';

var u250 = underscores(250);

      

0


source







All Articles