-2

How would you define a method that returns

"[Number of times]: hello hello hello [repeat Number of times]";

I want it to put in hello as many times my input wants it to display.

So, "number of times" is going to be there but i dont know how to do the hello.

My suggestion is,

return $"number of times: {string.Concat(Enumerable.Repeat("hello", num))}";

But the problem I get here is that there is no space between the hello's.

Could you help me please? I have been searching for hours but can't find a similar answer.

squillman
  • 13,363
  • 3
  • 41
  • 60
Mnda90
  • 27
  • 4

2 Answers2

4

Almost there, use String.Join instead of String.Concat, which allows you to add " " as a separator between elements

return $"number of times: {string.Join(" ", Enumerable.Repeat("hello", num))}";
djv
  • 15,168
  • 7
  • 48
  • 72
0

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object.

so I recommend this

StringBuilder sb = new StringBuilder($"number of times: {num} = hello");

for (int i = 0; i < num-1; i++) sb.Append( ", hello");

Console.WriteLine(sb.ToString());

result for num=12

number of times: 12 = hello, hello, hello, hello, hello, hello, hello, hello, hello, hello, hello, hello
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Related: https://stackoverflow.com/a/585897/832052 – djv Oct 08 '21 at 18:48
  • I would say specifically the immutability of string should be brought up wrt the Enumerable.Repeat, not String.Join – djv Oct 08 '21 at 18:49
  • @djv Yes, It is true. But in this case , there is no array, it is created and after this join is used. Even if .Join uses a string builder, direct way to use a string builder is always better. – Serge Oct 08 '21 at 18:51