开发者

Left Justify a String in C# with the length dynamically given

I am trying to write a Left Justi开发者_JAVA技巧fy Function such as:

private static string LeftJustify(string field, int len)
{
    string retVal = string.empty;

    ///todo:

   return retVal;

}

can you help me put the logic in the function?


If you're just trying to pad the string, you can use String.PadRight directly:

private static string LeftJustify(string field, int len)
{
    return field.PadRight(len);
}


You can use the string functions PadLeft or PadRight.

These will add spaces to a string, as many as needed.


From C# Examples:

To align string to the right or to the left use static method String.Format. To align string to the left (spaces on the right) use formatting pat[t]ern with comma (,) followed by a negative number of characters: String.Format("{0,–10}", text). To right alignment use a positive number: {0,10}

C#:

Console.WriteLine("-------------------------------");
Console.WriteLine("First Name | Last Name  |   Age");
Console.WriteLine("-------------------------------");
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Bill", "Gates", 51));
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Edna", "Parker", 114));
Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Johnny", "Depp", 44));
Console.WriteLine("-------------------------------");

Output:

 -------------------------------
 First Name | Last Name  |   Age
 -------------------------------
 Bill       | Gates      |    51
 Edna       | Parker     |   114
 Johnny     | Depp       |    44
 -------------------------------


You could use PadLeft explicitly

or use String.Format like this (which does most of the math)

String.Format("|{0,-10}|", field)
Output : if field="Fred"

|      Fred|


You'll want to add some parameter validation but this should work.

public static class Extensions
{
    static readonly char[] _whiteSpaceCharacters;

    static Extensions()
    {
        var r = new List<char>();
        for (char c = char.MinValue; c < char.MaxValue; c++)
            if (char.IsWhiteSpace(c))
                r.Add(c);
        _whiteSpaceCharacters = r.ToArray();
    }

    public static string LeftJustify(this string value)
    {
        return value.LeftJustify(4);
    }

    public static string LeftJustify(this string value, int length)
    {
        var sb = new StringBuilder();
        using (var sr = new StringReader(value))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(
                    line
                    .TrimStart(_whiteSpaceCharacters)
                    .PadLeft(length, ' ')
                );
            }
        }
        return sb.ToString();
    }
}

Input

     Line 1
         Line 2     
             Line 3
 Line 4

Output

     Line 1
     Line 2     
     Line 3
     Line 4


According to your comments you want to pad left with spaces. PadLeft() works for this, but you need to be aware of the 'totalWidth' parameter:

var s = "some text";
int paddingWidth = 4;

// example for no limit on line width
s.PadLeft(s.Length + paddingWidth, ' '); // results in "    someText"

But if there is a limit on the allowed line length, it will produce the wrong output (i.e. not pad with the desired amount of characters) and no error. You can even specify a totalWidth that is less than the total source string length.

If you want to always prepend a fixed amount of spaces, you can use this as well:

var padding = new StringBuilder();
padding.Append(' ', 5); // replace 5 with what's useful.
var result = padding + someString;

An alternative to spaces is tabulator characters, which will indent by some amount - often 4 spaces (depending on the context). That could be achieved by:

padding.Append('\t', count);

And so forth. You could put the logic for the padding in an extra method or extension method. Note, I didn't use the StringBuilder for efficiency reasons here. It is just convenient.


If you have a set length you want to maintain, and the string length varies, you could

while (retval.length < 21) { retval = " " + retval}

This would left pad the string until it is 20 characters long.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜