tags:

views:

128

answers:

3

What is the best/recommended way to add x number of occurances of a character to a string e.g.

String header = "HEADER";

The header variable needs to be have say 100 0's added to the end of it. But this number will change depending on other factors.

+10  A: 

How about:

header += new string('0', 100);

Of course; if you have multiple manipulations to make, consider StringBuilder:

StringBuilder sb = new StringBuilder("HEADER");
sb.Append('0', 100); // (actually a "fluent" API if you /really/ want...)
// other manipluations/concatenations (Append) here
string header = sb.ToString();
Marc Gravell
Note: If you know the final size of the string, specify that as capacity when creating the StringBuilder. It minimizes reallocations, and the result is a string object without a bunch of unused memory at the end.
Guffa
+3  A: 

This will append 100 zero characters to the string:

header += new string('0', 100);
Drew Noakes
+1 for showing the simplest possible solution, which is often best. Note however that it does **not** append characters to the string, it creates a new string with 100 zero characters, then creates another new string from the original string and the zeroes string.
Guffa
A: 

How about

string header = "Header";
header.PadRight(header.Length + 100, '0');
DarenFox
That doesn't work. You need header = header.PadRight(...);.
Guffa