Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a C# string with identical spacing in between values

Tags:

string

c#

I have 3 strings. The first set of strings are:

"1.0536"  
"2.1"  
"2" 

The second is something like:

"Round"  
"Square"  
"Hex"

And the last are:

"6061-T6"  
"T351"  
"ASF.3.4.5" 

I need to combine the three strings together with identical spacing in between each string. I can't use \t for tabbing as after I combine the strings, I send them to an Access Database.

When I combine the strings they look like:

"1.0536 Round 6061-T6"  
"2.1 Square T351"  
"2 Hex ASF.3.4.5" 

I would really like them to look like this with the same exact amount of spacing in between each string:

"1.0536     Round     6061-T6"
"2.1           Square    T351"
"2              Hex          ASF.3.4.5"

How can I do this with C#?

like image 380
fraXis Avatar asked Jan 24 '11 15:01

fraXis


People also ask

How do I format my C drive Windows 10?

Click on Drive options (advanced). Select Format among the options. Now, Windows will start the process of formatting your drive.

What happens if you format C drive?

All the data is removed, and space is made for new data and file systems. There are several different reasons for formatting a disk. You might be concerned about security, need to repurpose the hardware or want to install a new file system on your device.

Can we format C drive without CD?

If you want to reformat the hard drive, or C: drive, you cannot do so while Windows is running. You will need to boot the system from a boot disc first in order to conduct a PC format operation. If you don't have your Windows installation media, you can create a system repair disc from within Windows 7.

How do I format my C drive with USB?

How Do I Format A Hard Drive with A Flash Drive? Insert a USB into computer. Open File Explorer, and click This PC from the left panel. Under the "Device and drives" section, right-click the USB and choose "Format" option.


3 Answers

You can use advanced features of string.Format:

string.Format("{0,-10}{1,-10}{2}", ...) 

You can do the same thing by writing str.PadRight(10)

like image 191
SLaks Avatar answered Sep 29 '22 18:09

SLaks


If you know the maximum lengths of each column then do the following:

String result = String.Format("{0} {1} {2}", strCol1.PadRight(10), strCol2.PadRight(9), strCol3.PadRight(9));
like image 25
Martin Avatar answered Sep 29 '22 16:09

Martin


To make life easier, utility methods:

Usage

var data = new[] {
    new[] { "ID", "NAME", "DESCRIPTION" },
    new[] { "1", "Frank Foo", "lorem ipsum sic dolor" },
    new[] { "2", "Brandon Bar", "amet forthrightly" },
    new[] { "3", "B. Baz", "Yeehah!" }
};

var tabbedData = EvenColumns(20, data);
var tabbedData2 = string.Join("\n", EvenColumns(20, false, data)); // alternate line separator, alignment

Results

ID                  NAME                DESCRIPTION
1                   Frank Foo           lorem ipsum sic dolor
2                   Brandon Bar         amet forthrightly
3                   B. Baz              Yeehah!

ID                NAME         DESCRIPTION
1           Frank Foolorem ipsum sic dolor
2         Brandon Bar   amet forthrightly
3              B. Baz             Yeehah!

Code

public string EvenColumns(int desiredWidth, IEnumerable<IEnumerable<string>> lists) {
    return string.Join(Environment.NewLine, EvenColumns(desiredWidth, true, lists));
}

public IEnumerable<string> EvenColumns(int desiredWidth, bool rightOrLeft, IEnumerable<IEnumerable<string>> lists) {
    return lists.Select(o => EvenColumns(desiredWidth, rightOrLeft, o.ToArray()));
}

public string EvenColumns(int desiredWidth, bool rightOrLeftAlignment, string[] list, bool fitToItems = false) {
    // right alignment needs "-X" 'width' vs left alignment which is just "X" in the `string.Format` format string
    int columnWidth = (rightOrLeftAlignment ? -1 : 1) *
                        // fit to actual items? this could screw up "evenness" if
                        // one column is longer than the others
                        // and you use this with multiple rows
                        (fitToItems
                            ? Math.Max(desiredWidth, list.Select(o => o.Length).Max())
                            : desiredWidth
                        );

    // make columns for all but the "last" (or first) one
    string format = string.Concat(Enumerable.Range(rightOrLeftAlignment ? 0 : 1, list.Length-1).Select( i => string.Format("{{{0},{1}}}", i, columnWidth) ));

    // then add the "last" one without Alignment
    if(rightOrLeftAlignment) {
        format += "{" + (list.Length-1) + "}";
    }
    else {
        format = "{0}" + format;
    }

    return string.Format(format, list);
}

Specific to the Question

// for fun, assume multidimensional declaration rather than jagged
var data = new[,] {
    { "1.0536", "2.1", "2" },
    { "Round", "Square", "Hex" },
    { "6061-T6", "T351", "ASF.3.4.5" },
};

var tabbedData = EvenColumns(20, Transpose(ToJaggedArray(data)));

with Transpose:

public T[][] Transpose<T>(T[][] original) {
    // flip dimensions
    var h = original.Length;
    var w = original[0].Length;

    var result = new T[h][];
    for (var r = 0; r < h; r++) {
        result[r] = new T[w];
        for (var c = 0; c < w; c++)
        {
            result[r][c] = original[c][r];
        }
    }
    return result;
}

And multidimensional arrays (source):

public T[][] ToJaggedArray<T>(T[,] multiArray) {
    // via https://stackoverflow.com/questions/3010219/jagged-arrays-multidimensional-arrays-conversion-in-asp-net
    var h = multiArray.GetLength(0);
    var w = multiArray.GetLength(1);

    var result = new T[h][];
    for (var r = 0; r < h; r++) {
        result[r] = new T[w];
        for (var c = 0; c < w; c++) {
            result[r][c] = multiArray[r, c];
        }
    }
    return result;
}
like image 20
drzaus Avatar answered Sep 29 '22 18:09

drzaus