jorge_porto
jorge_porto

Reputation:

Append x occurrences of a character to a string in C#

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.

Upvotes: 19

Views: 14917

Answers (3)

Fen
Fen

Reputation: 943

How about

string header = "Header";
header = header.PadRight(header.Length + 100, '0');

Upvotes: 8

Drew Noakes
Drew Noakes

Reputation: 311335

This will append 100 zero characters to the string:

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

Upvotes: 12

Marc Gravell
Marc Gravell

Reputation: 1064204

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();

Upvotes: 39

Related Questions