c#定长字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19284216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:37:20  来源:igfitidea点击:

c# fixed length string

c#stringfixed-length-record

提问by VAAA

I need to generate a text line with a fixed lenght:

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

What I have right now is:

我现在拥有的是:

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)

This works great because generates a fixed lenght string of 55 characters.

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

The issue comes when for example the optional value is a empty string like:

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

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)

Having empty string inside the string.format then wont give a fixed length, and I still need to have a 30 chars length.

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

Any clue is well appreciated!!

任何线索都非常感谢!

Thanks

谢谢

回答by Szymon

You can use PadLeftmethod:

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

回答by Steve

Are you sure? Try to add a separator, just to see where the substrings end

你确定吗?尝试添加一个分隔符,只是为了看看子字符串在哪里结束

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|                              |<

回答by Pradeep

Not sure what is best way but following should work:

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

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

回答by Vas Gr

It will add up empty chars by default until the desired length matched.

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

Example: "Hello".ToFixedString(10)will produce "Hello ".

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