andrew4582

GetFixedLengthString

Jul 19th, 2012
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. /// <summary>
  2.         /// Finds the maximum length of a key and padd all the rest of the keys to be
  3.         /// the same fixed length, and calls the delegate supplied.
  4.         /// </summary>
  5.         /// <param name="keyValues">The key value pairs.</param>
  6.         /// <param name="extraPadding">Additional number of chars to pad to the keys.</param>
  7.         /// <param name="printer">The delegate to call to print to.</param>
  8.         public static void DoFixedLengthPrinting(IDictionary keyValues, int extraPadding,  Action<string, object> printer)
  9.         {
  10.             // Get the length of the longest named argument.
  11.             int maxLength = 0;
  12.             foreach (DictionaryEntry entry in keyValues)
  13.             {
  14.                 int keyLen = ((string)entry.Key).Length;
  15.                 if (keyLen > maxLength)
  16.                     maxLength = keyLen;
  17.             }
  18.             maxLength += extraPadding;
  19.  
  20.             // Iterate through all the keys and build a fixed length key.
  21.             // e.g. if key is 4 chars and maxLength is 6, add 2 chars using space(' ').
  22.             foreach (DictionaryEntry entry in keyValues)
  23.             {
  24.                 string newKeyWithPadding = GetFixedLengthString((string)entry.Key, maxLength, " ");
  25.                 printer(newKeyWithPadding, entry.Value);
  26.             }
  27.         }
  28.  
  29.  
  30.         /// <summary>
  31.         /// Builds a fixed length string with the maxChars provided.
  32.         /// </summary>
  33.         /// <param name="text">Current string to start with.</param>
  34.         /// <param name="maxChars">Maximum number of characters.</param>
  35.         /// <param name="paddingChar">Padding character.</param>
  36.         /// <returns>Final created string.</returns>
  37.         public static string GetFixedLengthString(string text, int maxChars, string paddingChar)
  38.         {
  39.             int leftOver = maxChars - text.Length;
  40.             string finalText = text;
  41.             for (int ndx = 0; ndx < leftOver; ndx++)
  42.                 finalText += paddingChar;
  43.             return finalText;
  44.         }
Advertisement
Add Comment
Please, Sign In to add comment