1

I want to repeat .- 40 times and save it to a string using StringBuilder

Why does this not work?

string result = new StringBuilder("").Append(".-",0,40).ToString();

I know about other Solutions but i want to use StringBuilder

Community
  • 1
  • 1
c0rd
  • 1,059
  • 1
  • 9
  • 18
  • Use a loop and add 40 times the same constant – Steve Sep 07 '16 at 12:19
  • 2
    That's not how `Append` works. You are telling it to append a substring not to repeat that string. Specifically the last argument is actually the length of the substring. They just gave it the unfortunate name of `count`. – juharr Sep 07 '16 at 12:19

3 Answers3

7

That method does not do what you think it does. The 2 int parameters specify the start index and length of the sub-string you want to append.

StringBuilder does have a method for what you want: It's called Insert:

sb.Insert(0, ".-", 40);
juharr
  • 30,127
  • 4
  • 48
  • 88
Dennis_E
  • 8,332
  • 20
  • 27
  • Yes, it is the length. Methods like these are confusing. In some methods the 2nd int means the end index, in other methods it means the length. Edited. – Dennis_E Sep 07 '16 at 12:28
  • Well most C# libraries go with start and length were as Java does the start and end. In this case it's even worse because they named the last argument `count`. – juharr Sep 07 '16 at 12:33
  • @juharr `Parallel.ForEach` for example uses start and end... I think I prefer that. "All numbers from 20 to 50" is clearer to me than "30 numbers starting from 20" – Dennis_E Sep 07 '16 at 12:37
1
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40; i++)
{
     sb.Append(".-");
}
MessageBox.Show(sb.ToString());
Balagurunathan Marimuthu
  • 2,666
  • 4
  • 23
  • 37
  • 1
    Dumping code is seldom useful for OP and for future readers, I'd also explain why he has not to initialize StringBuilder with an empty string, why his solution with Append() is wrong and why he may want to set initial capacity to 80 and how this is different with Insert()... – Adriano Repetti Sep 07 '16 at 12:23
0

If you want to repeat a string several times your options are:

1- Using a loop (as pointed by @Balagurunathan's answer)

2- For single characters you can use:

string result = new string('a', 10); //aaaaaaaaaa

For strings of more than one character:

string result = string.Join("", Enumerable.Repeat(".-", 5)) //.-.-.-.-.-

So I believe what you were trying to do was something along these lines:

string result = new StringBuilder().Append(string.Join("", Enumerable.Repeat(".-", 40))).ToString();

I would however stick to the for loop in terms of performance

Innat3
  • 3,456
  • 2
  • 8
  • 28