Martin
Martin

Reputation: 41

Help with string manipulation

I am doing some data manipulation and logging records that has been updated and their fields.

I have simplified the example below but basically I append rows to a stringbuilder and then write it to a text file

I append rows with:

changedValues.AppendLine(string.Format("NEW VALUE: {0} | OLD VALUE {1}", Customer1.name, Customer2.name));
changedValues.AppendLine(string.Format("NEW VALUE: {0} | OLD VALUE {1}", Customer1.number, Customer2.number));
changedValues.AppendLine(string.Format("NEW VALUE: {0} | OLD VALUE {1}", Customer1.phone, Customer2.phone))

My issue is that name, phone and number (plus many more) have different lengths so the log file looks something like:

NEW VALUE: blabla | OLD VALUE blablabla
NEW VALUE: 123123123123123 | OLD VALUE 134
NEW VALUE: 213213232 | OLD VALUE 12333322333

which makes it more difficult to read than if it looked something like:

NEW VALUE: blabla          | OLD VALUE blablabla
NEW VALUE: 123123123123123 | OLD VALUE 134
NEW VALUE: 213213232       | OLD VALUE 12333322333

How can I achieve this?

Thanks in advance.

Upvotes: 1

Views: 102

Answers (5)

cichy
cichy

Reputation: 10634

Customer1.name.PadRight(15, ' ')

And do the same for the other values.

Upvotes: 0

Alex Aza
Alex Aza

Reputation: 78447

Take a look at Composite formating

changedValues.AppendLine(string.Format("NEW VALUE: {0:-20} | OLD VALUE {1}", Customer1.name, Customer2.name));

Format is { index[,alignment][:formatString]}

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You should define in advance the longest possible first value. For example 20:

sb.AppendFormat("NEW VALUE: {0,-20}| OLD VALUE {1}\r\n", Customer1.name, Customer2.name);

Upvotes: 2

csano
csano

Reputation: 13676

If you know the maximum width of your values, you can use String.PadRight().

Upvotes: 0

danyolgiax
danyolgiax

Reputation: 13086

Use PadRight like this example:

static void Main()
{
string[] a = new string[]
{
    "cat",
    "poodle",
    "lizard",
    "frog",
    "photon"
};

// Output the header.
Console.Write("Key".PadRight(15));
Console.WriteLine("Value");

// Output array.
foreach (string s in a)
{
    Console.Write(s.PadRight(15));
    Console.WriteLine("noun");
}
}
Output

Key            Value
cat            noun
poodle         noun
lizard         noun
frog           noun
photon         noun

Upvotes: 0

Related Questions