18

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

String header = "HEADER";

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

Ola Ström
  • 4,136
  • 5
  • 22
  • 41

3 Answers3

38

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    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 Sep 10 '09 at 11:06
12

This will append 100 zero characters to the string:

header += new string('0', 100);
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 5
    +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 Sep 10 '09 at 11:11
8

How about

string header = "Header";
header = header.PadRight(header.Length + 100, '0');
ken2k
  • 48,145
  • 10
  • 116
  • 176
Fen
  • 933
  • 5
  • 13