c#固定长度字符串

时间:2013-10-09 22:57:12

标签: c# string fixed-length-record

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

我现在拥有的是:

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个字符长度。

任何线索都很受欢迎!!

由于

5 个答案:

答案 0 :(得分:8)

您可以使用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)

答案 1 :(得分: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|                              |<

答案 2 :(得分:0)

不确定什么是最好的方式,但以下应该有效:

string appended = string.Format("{0,5}", "MM");
appended += string.Format("{0,20}", "45444");
appended += string.Format("{0,30}", "");

答案 3 :(得分:0)

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

示例: "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()));
    }
}

答案 4 :(得分: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)           = "     "