Adjusting the width of strings in C#

By mkozelsky

For testing purposes, i’m printing some objects and their values to the console. I want to have nice columns which can be used to compare values and make sure the information is correct.

I search the Internet for about 10-15 minutes, and look at a lot of examples of string formatting, but nothing i found says “this will format the string to be exactly X number of characters”. Since i was just wasting time looking to no avail, i decided to write a method to do that. It’s not the most efficient thing, but it gets the job done.

Since this is only for testing purposes, this is OK. But there’s got to be something somewhere in the .NET framework to do this. Right?


private string AdjustLength(string stringToAdjust, int length)
{
    if (stringToAdjust.Length == length)
    {
        return stringToAdjust;
    }
    else if (stringToAdjust.Length > length)
    {
        return stringToAdjust.Substring(0, length);
    }
    else
    {
        int charsToAdd = length - stringToAdjust.Length;
        string result = stringToAdjust;
        for (int i = 0; i < charsToAdd; i++)
        {
            result += ' ';
        }
        return result;
    }
}

Tags: , , , , ,

Leave a Reply