c# fixed length string
Asked Answered
O

5

11

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.

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.

Any clue is well appreciated!!

Thanks

Onetime answered 9/10, 2013 at 22:57 Comment(3)
Use the String.PadLeft method : msdn.microsoft.com/en-us/library/92h5dc07.aspx to have a string of your desired width.Psychiatry
what happens if you pass in an blank space? _sb.Append(string.Format("{0,30}", " "));Higley
Your code, as is, still generates a 55 character long string, the last 30 of which are the space character.Overvalue
H
12

You can use PadLeft method:

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)
Heathenry answered 9/10, 2013 at 23:4 Comment(3)
when its empty the string the pad left is not workingOnetime
Sorry, I shouldn't have put String.Format in there. Check my edit.Heathenry
Not sure what's going on, my edit didn't go through. Now it's better.Heathenry
E
3

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|                              |<
Exhortation answered 9/10, 2013 at 23:7 Comment(1)
You should use _sb.AppendFormat()Idolatry
O
1

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

Example: "Hello".ToFixedString(10) will produce "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()));
    }
}
Otorhinolaryngology answered 3/10, 2018 at 0:13 Comment(1)
` if (value == null) return null; ` ... although there is much simpler version available.Labiate
L
1
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;

Example:

"1234567890".FixedStr(5) = "12345"
"12345".FixedStr(5)      = "12345"
"12".FixedStr(5)         = "12   "
"".FixedStr(5)           = "     "
Loy answered 29/6, 2020 at 21:16 Comment(0)
F
0

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}", "");
Flatto answered 9/10, 2013 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.