Search code examples
c#words

Align words in column


I'm quite new to C#, so I got a task to allign words in columns. So basically I've got a notepad with text in it for example: wordone word two... wordmillion and lets say there are 6lines of them. I need to set them in order so it would look like: word one word two word three wordjosdjfjfisio anotherword otherword

That each other word would start at a place like shown(extra space from longest word in first column and etc.) I tried to explain at as clearly as I could, any tips/ideas how do it? I think padright is the solution? P.S. sorry if the layout is wrong, I'm quite new to this community.


Solution

  • It looks like you are on the right track here!

    First of all, here is the documentation for PadRight:https://msdn.microsoft.com/en-us/library/36f2hz3a%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396.

    Taken from this MSDN explanation, we can see the following useful example:

    string str = "forty-two";
    char pad = '.';
    
    Console.WriteLine(str.PadRight(15, pad));    // Displays "forty-two......".
    Console.WriteLine(str.PadRight(2,  pad));    // Displays "forty-two".
    

    So a psuedo code algorithm for your answer could be the following - let me know if you need more explanation:

    1. Read all of the words in your file into a string array
    2. Find the length of the longest word, lets call it maxLength
    3. Go over all words and write them formatted in a table. You want to write them row by row, printing a newline after each row. For each row, take the number of columns you want to display (3 in your example).
    4. Instead of writing the word itself, you should use word.PadRight(maxLength + 1, ' ');

    Note - MaxLength + 1 is just so a space will be shown after your longest word as well. I hope this is enough info to get you on your way. Feel free to ask any follow up questions!