C# - Padding and Alignment
- Here’s a brief list of categories of these built-in methods so you can get an idea of what’s possible.
- Methods that add blank spaces for formatting purposes
(PadLeft(), PadRight())
- Methods that compare two strings or facilitate comparison
(Trim(), TrimStart(), TrimEnd(), GetHashcode(), the Length property)
- Methods that help you determine what’s inside of a string, or even retrieve just a part of the string
(Contains(), StartsWith(), EndsWith(), Substring())
- Methods that change the content of the string by replacing, inserting, or removing parts
(Replace(), Insert(), Remove())
- Methods that turn a string into an array of strings or characters
(Split(), ToCharArray())
- Methods that add blank spaces for formatting purposes
Formatting strings by adding whitespace before or after
- The PadLeft() method adds blank spaces to the left-hand side of the string so that the total number of characters equals the argument you send it. In this case, you want the total length of the string to be 12 characters.
1
2
string input = "Pad this";
Console.WriteLine(input.PadLeft(12));
- When you run the code, you observe four characters prefixed to the left of the string bring the length to 12 characters long.
- To add space or characters to the right side of your string, use the PadRight() method instead. 1. Update your code as follows:
1
Console.WriteLine(input.PadRight(12));
What is an overloaded method?
- In C#, an overloaded method is another version of a method with different or extra arguments that modify the functionality of the method slightly, as is the case with the overloaded version of the PadLeft() method.
- You can also call a second overloaded version of the method and pass in whatever character you want to use instead of a space. In this case, you fill the extra space with the dash character.
1
2
Console.WriteLine(input.PadLeft(12, '-'));
Console.WriteLine(input.PadRight(12, '-'));
- The output of the code is as follows:
1
2
----Pad this
Pad this----
Working with padded strings
Suppose you work for a payment processing company that still supports legacy mainframe systems. Often, those systems require data to be input in specific columns. For example, store the Payment ID in columns 1 through 6, the payee’s name in columns 7 through 30, and the Payment Amount in columns 31 through 40. Also, importantly, the Payment Amount is right-aligned.
You’re asked to build an application that will convert data in the relational database management system to the legacy file format. To ensure that the integration works correctly, the first step is to confirm the file format by giving the legacy system maintainers a sample of the output. Later, you build on this work to send hundreds or thousands of payments to be processed via an ASCII text file.
Here’s the code that you can use to format the payment data:
1
2
3
4
5
6
7
8
9
10
string paymentId = "769C";
string payeeName = "Mr. Stephen Ortega";
string paymentAmount = "$5,000.00";
var formattedLine = paymentId.PadRight(6);
formattedLine += payeeName.PadRight(24);
formattedLine += paymentAmount.PadLeft(10);
Console.WriteLine("1234567890123456789012345678901234567890");
Console.WriteLine(formattedLine);
- The output of the code is as follows:
1
2
1234567890123456789012345678901234567890
769C Mr. Stephen Ortega $5,000.00
- For the sales and marketing company’s newest investment products, you send thousands of personalized letters to the company’s existing clients. Your job is to write C# code to merge personalized information about the customer. The letter contains information like their existing portfolio and compares their current returns to projected returns if they were to invest in using the new products.
The writers have decided on the following example marketing message. Here’s the desired output (using fictitious customer account data).
1
2
3
4
5
6
7
8
9
10
11
Dear Ms. Barros,
As a customer of our Magic Yield offering we are excited to tell you about a new financial product that would dramatically increase your return.
Currently, you own 2,975,000.00 shares at a return of 12.75%.
Our new product, Glorious Future offers a return of 13.13%. Given your current volume, your potential profit would be ¤63,000,000.00.
Here's a quick comparison:
Magic Yield 12.75% $55,000,000.00
Glorious Future 13.13% $63,000,000.00
- Here’s the code that you can use to format the customer data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
string customerName = "Ms. Barros";
string currentProduct = "Magic Yield";
int currentShares = 2975000;
decimal currentReturn = 0.1275m;
decimal currentProfit = 55000000.0m;
string newProduct = "Glorious Future";
decimal newReturn = 0.13125m;
decimal newProfit = 63000000.0m;
Console.WriteLine($"Dear {customerName},");
Console.WriteLine($"As a customer of our {currentProduct} offering we are excited to tell you about a new financial product that would dramatically increase your return.\n");
Console.WriteLine($"Currently, you own {currentShares:N} shares at a return of {currentReturn:P}.\n");
Console.WriteLine($"Our new product, {newProduct} offers a return of {newReturn:P}. Given your current volume, your potential profit would be {newProfit:C}.\n");
Console.WriteLine("Here's a quick comparison:\n");
string comparisonMessage = "";
comparisonMessage = currentProduct.PadRight(20);
comparisonMessage += String.Format("{0:P}", currentReturn).PadRight(10);
comparisonMessage += String.Format("{0:C}", currentProfit).PadRight(20);
comparisonMessage += "\n";
comparisonMessage += newProduct.PadRight(20);
comparisonMessage += String.Format("{0:P}", newReturn).PadRight(10);
comparisonMessage += String.Format("{0:C}", newProfit).PadRight(20);
Console.WriteLine(comparisonMessage);