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