What is the best way to generate a string of \t
's in C#
I am learning C# and experimenting with different ways of saying the same thing.
Tabs(uint t)
is a function that returns a string
with t
amount of \t
's
For example Tabs(3)
returns "\t\t\t"
Which of these three ways of implementing Tabs(uint numTabs)
is best?
Of course that depends on what "best" means.
The LINQ version is only two lines, which is nice. But are the calls to Repeat and Aggregate unnecessarily time/resource consuming?
The StringBuilder
version is very clear but is the StringBuilder
class somehow slower?
The string
version is basic, which means it is easy to understand.
Does it not matter at all? Are they all equal?
These are all questions to help me get a better feel for C#.
private string Tabs(uint numTabs) { IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs); return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : ""; } private string Tabs(uint numTabs) { StringBuilder sb = new StringBuilder(); for (uint i = 0; i < numTabs; i++) sb.Append("\t"); return sb.ToString(); } private string Tabs(uint numTabs) { string output = ""; for (uint i = 0; i < numTabs; i++) { output += '\t'; } return output; }
It use the function "strcat()" from the "string. h", so do not forget include this header. Show activity on this post. Here's a way to repeat a string in C, N times.
No, you can't do this in 'C' as far as I think.In python multiplication of a string by a number is defined as 'repetition' of the string that number of times. One way you can do this in 'C++'(a superset of 'C' language) is through 'operator overloading'.
Repeat String X Times With the LINQ Method in C# We can use the Enumerable. Repeat() function of LINQ to repeat a string x number of times in C#. The Enumerable. Repeat(s, x) function takes two parameters, the string variable s and the integer variable x , the number of times that string variable must be repeated.
Start with the first character, loop through the rest of the string to see if it matches. if there is no match, then repeat for the next character.
What about this:
string tabs = new string('\t', n);
Where n
is the number of times you want to repeat the string.
Or better:
static string Tabs(int n) { return new string('\t', n); }
string.Concat(Enumerable.Repeat("ab", 2));
Returns
"abab"
And
string.Concat(Enumerable.Repeat("a", 2));
Returns
"aa"
from...
Is there a built-in function to repeat string or char in .net?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With