Question: Is There A Way To Format White-space Like This In C#?












-2














Is There A Way To Format White-space Like This In C#?



I would like to know if you could parse string arrays into a method and get it to return you a formatted string with white-spaces, there is a specific way i need this done so here's an example:



string StringArray = new string {
new string {"Name:", "John Jones."}
new string {"Date of birth:", "07/11/1989."}
new string {"Age:", "29 Years old."}
};

FormatWhiteSpace(StringArray, Padding: 5);


Output would be:



Name:              John Jones.
Date of birth: 07/11/1989.
Age: 29 Years old.


As you see above in the output everything is lined up and with 5 spaces for padding as defined when we called the method. This is exactly what we want. Also we have a 2 dimensional array because that allows us to parse in more than 1 line at once. Here's another example, this time with more than two columns:



string StringArray = new string {
new string {"Name:", "John", "Jones."}
new string {"Date of birth:", "Monday,", "07/11/1989."}
new string {"Age:", "29", "Years old."}
};

FormatWhiteSpace(StringArray, Padding: 2);


Second Output would be:



Name:           John     Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.



That's all i would like to know if you know of anything that can help
me please let me know. Thanks for your help, you guys really made my
day.











share|improve this question


















  • 2




    If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
    – InBetween
    Nov 20 at 20:56












  • I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
    – RanOutOfQuestions
    Nov 20 at 20:59








  • 2




    This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
    – InBetween
    Nov 20 at 21:00












  • Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
    – Flydog57
    Nov 20 at 21:01








  • 1




    Possible duplicate of .NET Format a string with fixed spaces
    – Wayne Phipps
    Nov 20 at 21:04
















-2














Is There A Way To Format White-space Like This In C#?



I would like to know if you could parse string arrays into a method and get it to return you a formatted string with white-spaces, there is a specific way i need this done so here's an example:



string StringArray = new string {
new string {"Name:", "John Jones."}
new string {"Date of birth:", "07/11/1989."}
new string {"Age:", "29 Years old."}
};

FormatWhiteSpace(StringArray, Padding: 5);


Output would be:



Name:              John Jones.
Date of birth: 07/11/1989.
Age: 29 Years old.


As you see above in the output everything is lined up and with 5 spaces for padding as defined when we called the method. This is exactly what we want. Also we have a 2 dimensional array because that allows us to parse in more than 1 line at once. Here's another example, this time with more than two columns:



string StringArray = new string {
new string {"Name:", "John", "Jones."}
new string {"Date of birth:", "Monday,", "07/11/1989."}
new string {"Age:", "29", "Years old."}
};

FormatWhiteSpace(StringArray, Padding: 2);


Second Output would be:



Name:           John     Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.



That's all i would like to know if you know of anything that can help
me please let me know. Thanks for your help, you guys really made my
day.











share|improve this question


















  • 2




    If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
    – InBetween
    Nov 20 at 20:56












  • I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
    – RanOutOfQuestions
    Nov 20 at 20:59








  • 2




    This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
    – InBetween
    Nov 20 at 21:00












  • Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
    – Flydog57
    Nov 20 at 21:01








  • 1




    Possible duplicate of .NET Format a string with fixed spaces
    – Wayne Phipps
    Nov 20 at 21:04














-2












-2








-2







Is There A Way To Format White-space Like This In C#?



I would like to know if you could parse string arrays into a method and get it to return you a formatted string with white-spaces, there is a specific way i need this done so here's an example:



string StringArray = new string {
new string {"Name:", "John Jones."}
new string {"Date of birth:", "07/11/1989."}
new string {"Age:", "29 Years old."}
};

FormatWhiteSpace(StringArray, Padding: 5);


Output would be:



Name:              John Jones.
Date of birth: 07/11/1989.
Age: 29 Years old.


As you see above in the output everything is lined up and with 5 spaces for padding as defined when we called the method. This is exactly what we want. Also we have a 2 dimensional array because that allows us to parse in more than 1 line at once. Here's another example, this time with more than two columns:



string StringArray = new string {
new string {"Name:", "John", "Jones."}
new string {"Date of birth:", "Monday,", "07/11/1989."}
new string {"Age:", "29", "Years old."}
};

FormatWhiteSpace(StringArray, Padding: 2);


Second Output would be:



Name:           John     Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.



That's all i would like to know if you know of anything that can help
me please let me know. Thanks for your help, you guys really made my
day.











share|improve this question













Is There A Way To Format White-space Like This In C#?



I would like to know if you could parse string arrays into a method and get it to return you a formatted string with white-spaces, there is a specific way i need this done so here's an example:



string StringArray = new string {
new string {"Name:", "John Jones."}
new string {"Date of birth:", "07/11/1989."}
new string {"Age:", "29 Years old."}
};

FormatWhiteSpace(StringArray, Padding: 5);


Output would be:



Name:              John Jones.
Date of birth: 07/11/1989.
Age: 29 Years old.


As you see above in the output everything is lined up and with 5 spaces for padding as defined when we called the method. This is exactly what we want. Also we have a 2 dimensional array because that allows us to parse in more than 1 line at once. Here's another example, this time with more than two columns:



string StringArray = new string {
new string {"Name:", "John", "Jones."}
new string {"Date of birth:", "Monday,", "07/11/1989."}
new string {"Age:", "29", "Years old."}
};

FormatWhiteSpace(StringArray, Padding: 2);


Second Output would be:



Name:           John     Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.



That's all i would like to know if you know of anything that can help
me please let me know. Thanks for your help, you guys really made my
day.








c# formatting whitespace






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 20:49









RanOutOfQuestions

22




22








  • 2




    If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
    – InBetween
    Nov 20 at 20:56












  • I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
    – RanOutOfQuestions
    Nov 20 at 20:59








  • 2




    This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
    – InBetween
    Nov 20 at 21:00












  • Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
    – Flydog57
    Nov 20 at 21:01








  • 1




    Possible duplicate of .NET Format a string with fixed spaces
    – Wayne Phipps
    Nov 20 at 21:04














  • 2




    If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
    – InBetween
    Nov 20 at 20:56












  • I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
    – RanOutOfQuestions
    Nov 20 at 20:59








  • 2




    This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
    – InBetween
    Nov 20 at 21:00












  • Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
    – Flydog57
    Nov 20 at 21:01








  • 1




    Possible duplicate of .NET Format a string with fixed spaces
    – Wayne Phipps
    Nov 20 at 21:04








2




2




If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
– InBetween
Nov 20 at 20:56






If you are asking if there is an inbuilt way to do this, then the answer is no, but you can obviously write code that behaves the way you require; string.PadRight looks like a good starting point.
– InBetween
Nov 20 at 20:56














I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
– RanOutOfQuestions
Nov 20 at 20:59






I'm asking if anyone knows how. I would like an in-built way but if there isn't then I'm asking if someone could create code or direct me towards creating it. And thanks for the advice.
– RanOutOfQuestions
Nov 20 at 20:59






2




2




This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
– InBetween
Nov 20 at 21:00






This isnt a place where people write code for you. This is a place where you ask about specific problems in your code that you don't know how to solve.
– InBetween
Nov 20 at 21:00














Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
– Flydog57
Nov 20 at 21:01






Make two passes through the main (rows) array. On the first pass, Create a second collection that consists of the max widths of each column. On the second pass, output each string padded using the information about the max width of the column it's in (plus a little extra).
– Flydog57
Nov 20 at 21:01






1




1




Possible duplicate of .NET Format a string with fixed spaces
– Wayne Phipps
Nov 20 at 21:04




Possible duplicate of .NET Format a string with fixed spaces
– Wayne Phipps
Nov 20 at 21:04












2 Answers
2






active

oldest

votes


















0














Try something like this (I added an extra row to your data to make it not square and make debugging more obvious):



public static class PaddedColumns
{
private static string _stringArray = new string {
new {"Name:", "John", "Jones."},
new {"Date of birth:", "Monday,", "07/11/1989."},
new {"Age:", "29", "Years old."},
new {"Eye Color:", "blue", ""},
};

public static void PadIt()
{
OutputPadded(_stringArray);
}

public static void OutputPadded(string strings)
{
var columnMaxes = new int[strings[0].Length];

foreach (var row in strings)
{
for (var colNo = 0; colNo < row.Length; ++colNo)
{
if (row[colNo].Length > columnMaxes[colNo])
{
columnMaxes[colNo] = row[colNo].Length;
}
}
}

const int extraPadding = 2;

//got the maxes, now go through and use them to pad things
foreach (var row in strings)
{
for (var colNo = 0; colNo < row.Length; ++colNo)
{
Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
}
Console.WriteLine("");
}

}

}


The result looks like:



Name:           John     Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.
Eye Color: blue





share|improve this answer





















  • One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
    – Flydog57
    Nov 20 at 23:28



















0














I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.



void Main()
{
string StringArray = new string {
new {"Name:", "John", "Jones."},
new {"Date of birth:", "Monday,", "07/11/1989."},
new {"Age:", "29", "Years old."}};

var lines = FormatWhiteSpace(StringArray, Padding: 2);

foreach (var line in lines)
{
Console.WriteLine(line);
}
}

private IEnumerable<string> FormatWhiteSpace(string StringArray, int Padding)
{
var maxLengthDict = StringArray
.Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
.SelectMany(x => x)
.GroupBy(x => x.Column)
.Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
.ToDictionary(x => x.Column, x => x.MaxLength);

return StringArray
.Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401292%2fquestion-is-there-a-way-to-format-white-space-like-this-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Try something like this (I added an extra row to your data to make it not square and make debugging more obvious):



    public static class PaddedColumns
    {
    private static string _stringArray = new string {
    new {"Name:", "John", "Jones."},
    new {"Date of birth:", "Monday,", "07/11/1989."},
    new {"Age:", "29", "Years old."},
    new {"Eye Color:", "blue", ""},
    };

    public static void PadIt()
    {
    OutputPadded(_stringArray);
    }

    public static void OutputPadded(string strings)
    {
    var columnMaxes = new int[strings[0].Length];

    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    if (row[colNo].Length > columnMaxes[colNo])
    {
    columnMaxes[colNo] = row[colNo].Length;
    }
    }
    }

    const int extraPadding = 2;

    //got the maxes, now go through and use them to pad things
    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
    }
    Console.WriteLine("");
    }

    }

    }


    The result looks like:



    Name:           John     Jones.
    Date of birth: Monday, 07/11/1989.
    Age: 29 Years old.
    Eye Color: blue





    share|improve this answer





















    • One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
      – Flydog57
      Nov 20 at 23:28
















    0














    Try something like this (I added an extra row to your data to make it not square and make debugging more obvious):



    public static class PaddedColumns
    {
    private static string _stringArray = new string {
    new {"Name:", "John", "Jones."},
    new {"Date of birth:", "Monday,", "07/11/1989."},
    new {"Age:", "29", "Years old."},
    new {"Eye Color:", "blue", ""},
    };

    public static void PadIt()
    {
    OutputPadded(_stringArray);
    }

    public static void OutputPadded(string strings)
    {
    var columnMaxes = new int[strings[0].Length];

    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    if (row[colNo].Length > columnMaxes[colNo])
    {
    columnMaxes[colNo] = row[colNo].Length;
    }
    }
    }

    const int extraPadding = 2;

    //got the maxes, now go through and use them to pad things
    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
    }
    Console.WriteLine("");
    }

    }

    }


    The result looks like:



    Name:           John     Jones.
    Date of birth: Monday, 07/11/1989.
    Age: 29 Years old.
    Eye Color: blue





    share|improve this answer





















    • One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
      – Flydog57
      Nov 20 at 23:28














    0












    0








    0






    Try something like this (I added an extra row to your data to make it not square and make debugging more obvious):



    public static class PaddedColumns
    {
    private static string _stringArray = new string {
    new {"Name:", "John", "Jones."},
    new {"Date of birth:", "Monday,", "07/11/1989."},
    new {"Age:", "29", "Years old."},
    new {"Eye Color:", "blue", ""},
    };

    public static void PadIt()
    {
    OutputPadded(_stringArray);
    }

    public static void OutputPadded(string strings)
    {
    var columnMaxes = new int[strings[0].Length];

    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    if (row[colNo].Length > columnMaxes[colNo])
    {
    columnMaxes[colNo] = row[colNo].Length;
    }
    }
    }

    const int extraPadding = 2;

    //got the maxes, now go through and use them to pad things
    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
    }
    Console.WriteLine("");
    }

    }

    }


    The result looks like:



    Name:           John     Jones.
    Date of birth: Monday, 07/11/1989.
    Age: 29 Years old.
    Eye Color: blue





    share|improve this answer












    Try something like this (I added an extra row to your data to make it not square and make debugging more obvious):



    public static class PaddedColumns
    {
    private static string _stringArray = new string {
    new {"Name:", "John", "Jones."},
    new {"Date of birth:", "Monday,", "07/11/1989."},
    new {"Age:", "29", "Years old."},
    new {"Eye Color:", "blue", ""},
    };

    public static void PadIt()
    {
    OutputPadded(_stringArray);
    }

    public static void OutputPadded(string strings)
    {
    var columnMaxes = new int[strings[0].Length];

    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    if (row[colNo].Length > columnMaxes[colNo])
    {
    columnMaxes[colNo] = row[colNo].Length;
    }
    }
    }

    const int extraPadding = 2;

    //got the maxes, now go through and use them to pad things
    foreach (var row in strings)
    {
    for (var colNo = 0; colNo < row.Length; ++colNo)
    {
    Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
    }
    Console.WriteLine("");
    }

    }

    }


    The result looks like:



    Name:           John     Jones.
    Date of birth: Monday, 07/11/1989.
    Age: 29 Years old.
    Eye Color: blue






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 at 21:48









    Flydog57

    1,7442510




    1,7442510












    • One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
      – Flydog57
      Nov 20 at 23:28


















    • One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
      – Flydog57
      Nov 20 at 23:28
















    One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
    – Flydog57
    Nov 20 at 23:28




    One thing to note is that @carloBos's and my solution use the same algorithm, just with two radically different implementations. If you aren't going to use LINQ, and you want to return a collection of fully formed lines (as does @CarloBos), consider using a StringBuilder rather than using straight-up string concatenation. I've yet to find a good way to concatenate things using StringBuilders and LINQ.
    – Flydog57
    Nov 20 at 23:28













    0














    I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.



    void Main()
    {
    string StringArray = new string {
    new {"Name:", "John", "Jones."},
    new {"Date of birth:", "Monday,", "07/11/1989."},
    new {"Age:", "29", "Years old."}};

    var lines = FormatWhiteSpace(StringArray, Padding: 2);

    foreach (var line in lines)
    {
    Console.WriteLine(line);
    }
    }

    private IEnumerable<string> FormatWhiteSpace(string StringArray, int Padding)
    {
    var maxLengthDict = StringArray
    .Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
    .SelectMany(x => x)
    .GroupBy(x => x.Column)
    .Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
    .ToDictionary(x => x.Column, x => x.MaxLength);

    return StringArray
    .Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
    }





    share|improve this answer


























      0














      I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.



      void Main()
      {
      string StringArray = new string {
      new {"Name:", "John", "Jones."},
      new {"Date of birth:", "Monday,", "07/11/1989."},
      new {"Age:", "29", "Years old."}};

      var lines = FormatWhiteSpace(StringArray, Padding: 2);

      foreach (var line in lines)
      {
      Console.WriteLine(line);
      }
      }

      private IEnumerable<string> FormatWhiteSpace(string StringArray, int Padding)
      {
      var maxLengthDict = StringArray
      .Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
      .SelectMany(x => x)
      .GroupBy(x => x.Column)
      .Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
      .ToDictionary(x => x.Column, x => x.MaxLength);

      return StringArray
      .Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
      }





      share|improve this answer
























        0












        0








        0






        I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.



        void Main()
        {
        string StringArray = new string {
        new {"Name:", "John", "Jones."},
        new {"Date of birth:", "Monday,", "07/11/1989."},
        new {"Age:", "29", "Years old."}};

        var lines = FormatWhiteSpace(StringArray, Padding: 2);

        foreach (var line in lines)
        {
        Console.WriteLine(line);
        }
        }

        private IEnumerable<string> FormatWhiteSpace(string StringArray, int Padding)
        {
        var maxLengthDict = StringArray
        .Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
        .SelectMany(x => x)
        .GroupBy(x => x.Column)
        .Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
        .ToDictionary(x => x.Column, x => x.MaxLength);

        return StringArray
        .Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
        }





        share|improve this answer












        I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.



        void Main()
        {
        string StringArray = new string {
        new {"Name:", "John", "Jones."},
        new {"Date of birth:", "Monday,", "07/11/1989."},
        new {"Age:", "29", "Years old."}};

        var lines = FormatWhiteSpace(StringArray, Padding: 2);

        foreach (var line in lines)
        {
        Console.WriteLine(line);
        }
        }

        private IEnumerable<string> FormatWhiteSpace(string StringArray, int Padding)
        {
        var maxLengthDict = StringArray
        .Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
        .SelectMany(x => x)
        .GroupBy(x => x.Column)
        .Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
        .ToDictionary(x => x.Column, x => x.MaxLength);

        return StringArray
        .Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 22:05









        Carlo Bos

        663411




        663411






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401292%2fquestion-is-there-a-way-to-format-white-space-like-this-in-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'