8

我需要生成一个固定长度的文本行:

我现在拥有的是:

StringBuilder _sb = new StringBuilder();

_sb.Append(string.Format("{0,5}", "MM")); // serie to cancel
_sb.Append(string.Format("{0,20}", "45444")); // folio to cancel
_sb.Append(string.Format("{0,30}", "AC1122")); // account number (optional)

这很有效,因为生成了 55 个字符的固定长度字符串。

例如,当可选值是一个空字符串时,就会出现问题,例如:

StringBuilder _sb = new StringBuilder();

_sb.Append(string.Format("{0,5}", "MM")); // serie to cancel
_sb.Append(string.Format("{0,20}", "45444")); // folio to cancel
_sb.Append(string.Format("{0,30}", "")); // account number (optional)

在 string.format 中有空字符串不会给出固定长度,我仍然需要有 30 个字符的长度。

任何线索都非常感谢!

谢谢

4

5 回答 5

10

您可以使用PadLeft方法:

StringBuilder _sb = new StringBuilder();

_sb.Append("MM".PadLeft(5)); // serie to cancel
_sb.Append("45444".PadLeft(20)); // folio to cancel
_sb.Append("".PadLeft(30)); // account number (optional)
于 2013-10-09T23:04:15.320 回答
2

你确定吗?尝试添加分隔符,只是为了查看子字符串的结束位置

StringBuilder _sb = new StringBuilder();
_sb.Append(string.Format("{0,5}|", "MM")); // serie to cancel
_sb.Append(string.Format("{0,20}|", "45444")); // folio to cancel
_sb.Append(string.Format("{0,30}|", "")); // account number (optional
Console.WriteLine(">" + _sb.ToString() + "<");

>   MM|               45444|                              |<
于 2013-10-09T23:07:22.370 回答
1

默认情况下,它将添加空字符,直到所需的长度匹配。

示例: "Hello".ToFixedString(10)将产生"Hello ".

public static class StringExtensions
{
    /// <summary>
    /// Extends the <code>String</code> class with this <code>ToFixedString</code> method.
    /// </summary>
    /// <param name="value"></param>
    /// <param name="length">The prefered fixed string size</param>
    /// <param name="appendChar">The <code>char</code> to append</param>
    /// <returns></returns>
    public static String ToFixedString(this String value, int length, char appendChar = ' ')
    {
        int currlen = value.Length;
        int needed = length == currlen ? 0 : (length - currlen);

        return needed == 0 ? value :
            (needed > 0 ? value + new string(' ', needed) :
                new string(new string(value.ToCharArray().Reverse().ToArray()).
                    Substring(needed * -1, value.Length - (needed * -1)).ToCharArray().Reverse().ToArray()));
    }
}
于 2018-10-03T00:13:10.547 回答
0

不知道什么是最好的方法,但以下应该工作:

string appended = string.Format("{0,5}", "MM");
appended += string.Format("{0,20}", "45444");
appended += string.Format("{0,30}", "");
于 2013-10-09T23:14:11.040 回答
0
public static String FixedStr(this string s, int length, char padChar = ' ')
        => String.IsNullOrEmpty(s) ? new string(padChar, length) : s.Length > length ? s.Remove(length) : s.Length < length ? s.PadRight(length) : s;

例子:

"1234567890".FixedStr(5) = "12345"
"12345".FixedStr(5)      = "12345"
"12".FixedStr(5)         = "12   "
"".FixedStr(5)           = "     "
于 2020-06-29T21:16:03.213 回答