Creating C # strings by number of characters
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 to share
var myString = "__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________";
Why do you want to generate it? And why do you want to avoid the loop for
?
0
source to share
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 to share