Repeating a character X number of times?

  • Thread starter Thread starter David Veeneman
  • Start date Start date
D

David Veeneman

What function do I use to repeat a character X number of times? For example,
say I want to create a string with 40 dashes.

Thanks in advance
 
Hello David,

string dash = "";
for (int i = 0; i < 40; i++)
{
dash += "'";
}

DV> What function do I use to repeat a character X number of times? For
DV> example, say I want to create a string with 40 dashes.
DV>
DV> Thanks in advance
DV>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
You realize, of course, that this method actually creates 40 different
strings objects don't you? Since strings are immutable, whenever you
assign a value to an existing string or append to an existing string, a
new string is created of the appropriate size and the contents placed
in it.

Better to use the appropriate string constructor as Tim suggested.
 
that this method actually creates 40 different strings objects don't you?

um... 80 string objects

dash += ""

is essentially the same as:
dash = new string (dash + new string("-"))
 
System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append('x', 40);

//sb.ToString();

SA
 
um... 80 string objects
dash += ""

is essentially the same as:
dash = new string (dash + new string("-"))


Except that string literals normally gets interned so you get the same
object every time.


Mattias
 
David Veeneman said:
What function do I use to repeat a character X number of times? For example,
say I want to create a string with 40 dashes.

If you really do want to create a string with 40 dashes (rather than
creating a string with an arbitrary number of arbitrary characters)
then the fastest solution is

string s = "----------------------------------------"; // 40 dashes
 
Tim sollution is definitly elegant, I was a bit tired and didn't catch this

But, using string to concatinate 40,80,200,2000 symbols hardly make sence
for performance, you even don't see the difference.
You realize, of course, that this method actually creates 40 different
strings objects don't you? Since strings are immutable, whenever you
assign a value to an existing string or append to an existing string, a
new string is created of the appropriate size and the contents placed
in it.

--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
Back
Top