3

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

2
  • Use a loop and add 40 times the same constant Commented Sep 7, 2016 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. Commented Sep 7, 2016 at 12:19

3 Answers 3

11

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 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"
1
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 40; i++)
{
     sb.Append(".-");
}
MessageBox.Show(sb.ToString());

1 Comment

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()...
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.