Home > Back-end >  Write "Hello" multiple times in the same line [duplicate]
Write "Hello" multiple times in the same line [duplicate]

Time:10-09

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.

CodePudding user response:

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))}";

CodePudding user response:

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
  •  Tags:  
  • c#
  • Related