• El Tranquilo (unregistered)

    I hope the "case 81" is a type of the submitter...

  • (nodebb)

    81 FTW?

    I'm always amazing how RTFM still is the best way to identify bad developers even without obvious sloppy mistakes :-)

  • (nodebb)

    The limit of 9 padding zeroes is less bothersome, since AFAIK in C#, int is 32 bits(1), but there's still no point in writing code like this when there's so many built-in options for padding.

    (1) In C/C++, on the other hand, it would make my portability teeth itch, since C/C++ allows int to be any length not shorter than short and not longer than long, so it might be 64 bits...

  • (nodebb) in reply to MaxiTB

    ChatGPT joined our competition:

    Sure! If you want to avoid using the built-in PadLeft method and implement the padding logic manually, you can construct a fast solution by pre-allocating a char array and filling it appropriately. This avoids unnecessary memory allocations and ensures good performance.

    Here’s how you can implement it:

    public static string PadWithZeroes(string input, int totalWidth)
    {
        int inputLength = input.Length;
        
        // If the input string is already of required length or longer, return it as is
        if (inputLength >= totalWidth)
        {
            return input;
        }
        
        // Calculate how many zeroes are needed
        int zeroCount = totalWidth - inputLength;
        
        // Create a new char array with the total width
        char[] result = new char[totalWidth];
        
        // Fill the beginning with zeroes
        for (int i = 0; i < zeroCount; i++)
        {
            result[i] = '0';
        }
        
        // Copy the original string characters to the result array
        for (int i = 0; i < inputLength; i++)
        {
            result[zeroCount + i] = input[i];
        }
        
        // Convert the char array to a string and return it
        return new string(result);
    }
    
  • (nodebb)

    I once needed to leftpad a string, but it was with a weird character, so I could not use a built-in. I did

    return "*********".substring(0, length - string.length) + string;

    It looks really stupid, yet I can't think of a better way.

  • Jonathan (unregistered)

    With lowercase "l" on .length, this isn't C#, probably Java.

  • DQ (unregistered) in reply to Barbaz

    I'll admit I sometimes use something like this: Return Right('*******************' & input.ToString(), DesiredLength)

  • Sauron (unregistered)

    I never touched C# , so I have a question. Since there's no return statement in that ZeroPadString() function, does the code crash or try to guess the variable to return (and in such case, does it know for sure thatresult is the variable that must be returned?)

  • (nodebb) in reply to Barbaz

    https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft?view=net-8.0#system-string-padleft(system-int32-system-char)

  • (nodebb) in reply to Jonathan

    You are right - I thought it's a Java developer trying to develop something in C# but now I think it's a Java developer doing his normal thing. It makes all sense now :-).

  • Gaetan (unregistered)

    It the «case 81» a typo or a sub-WTF ?

  • (nodebb) in reply to Mr. TA

    Ha, I'm not sure if ChatGPT copied the right implementation there for .net; the actual code looks like this:

            public string PadLeft(int totalWidth, char paddingChar)
            {
                ArgumentOutOfRangeException.ThrowIfNegative(totalWidth);
                int oldLength = Length;
                int count = totalWidth - oldLength;
                if (count <= 0)
                    return this;
    
                string result = FastAllocateString(totalWidth);
    
                new Span<char>(ref result._firstChar, count).Fill(paddingChar);
                Buffer.Memmove(ref Unsafe.Add(ref result._firstChar, count), ref _firstChar, (nuint)oldLength);
    
                return result;
            }
    
  • Gaetan (unregistered) in reply to Gaetan

    Funny that all the previous similar comments were «held for moderation» at the time of writing! Sorry for the duplicate then (unless it is a feature, with so many articles showing unnecessary code duplications).

  • (nodebb) in reply to Steve_The_Cynic

    While int could be longer than 32 bits, you can't portably depend on it. So you shouldn't use int for something that might be bigger, and 10 digits is enough for portable callers.

  • Naomi (unregistered)

    String is written with an upper-case S in Java, and there's no operator overloading, so it can't be some custom string implementation. This method is also lacking a return, so I don't think it's valid in either language.

  • Argle (unregistered) in reply to Sauron

    I'm guessing a slipup in the editing process. Yes, the return is required.

  • LZ79LRU (unregistered) in reply to MaxiTB

    Try this on for size:

    	static string Pad(char padder, string source, int left, int right)
    	{
    		char[] stig = source.ToArray();
    		char[] total = new char[left + stig.Length + right];
    		for (int i = 0; i < left + stig.Length + right; i++)
    		{
    			switch (i)
    			{
    				case int n when (n < left):
    				default:
    				{
    					total[i] = padder;
    					break;
    				}
    				case int n when (n >= left && n < left + stig.Length):
    				{
    					total[i] = stig[i - left];
    					break;
    				}
    			}
    		}
    		string result = string.Join("", total);
    		return result;
    	}
    

    Excuse the formatting when it inevitably breaks.

  • Duston (unregistered)

    Why does it matter how many bits the language supports? This is zero padding a string, so it's probably to print a report or make sure some strings sort numerically instead of alphabetically or store in some sort of a fixed length record.

    The Case 81 is odd, but probably a fat finger since l is right next to :. Verdict? WTF.

  • (nodebb) in reply to Barry Margolin

    While int could be longer than 32 bits, you can't portably depend on it.

    Indeed, although my point was that you can't portably depend on it being only 32 bits (or shorter), so 9 is the wrong maximum pad size.

  • Steve (unregistered)

    I'm just happy that value is always a non-negative integer. Right?

  • ZZartin (unregistered)

    I'm more triggered that they aren't null checking before getting the length, but maybe that's not an issue in C#, java would definitely cry about it.

  • Die Kuhe (kein roboter) (unregistered)

    sprintf(s,"%099d",value)...

  • Marjancek (unregistered)

    isn't it obvious?

    public static string PadWithZeroes(string input, int totalWidth) { if (input.Length >= totalWidth){ return input; } return PadWithZeroes("0"+input, totalWidth-1) }

  • Foo AKA Fooo (unregistered) in reply to Steve_The_Cynic

    Especially since the function is not for padding (stringified) integers, but arbitrary strings.

  • (nodebb)

    Two minutes of Googling gave me:

    C# (https://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times) string result = new String('-', 5);

    I already knew Java had a String.repeat() but Googled to find out it's in Java 11+: String result = "-".repeat(5);

    Of course, in Java I'd do a variant of: String.format("%0" + n + "d", number);

    Unsure about C#...

  • Officer Johnny Holzkopf (unregistered) in reply to Steve_The_Cynic

    In this specific case, it is not important how many number symbols the value can have, because it can have more than int or even long can hold. Remember the method's signature: "public static string ZeroPadString(string _value, int _length)" - _value is a string, so you could call String s = ZeroPadString("3502658762499502744769673496362914826758701232312587624234387", -12); without "problems"...

  • löchlein deluxe (unregistered)

    In the spirit of "technically correct, which is the best kind of correct": use a language with lazy evaluation, reverse the numbers, add a generator for infinitely many padding chars, take what you need, and reverse again. That's probably one line in Haskell.

  • (nodebb) in reply to Erik

    In C# you should always use string interpolation for string construction except in those two cases:

    1. You are doing it in an iteration, use StringBuilder instead.

    2. You absolutely know what you are doing and how the language is not only designed but where the design time is heading to in the future (aka you read git csharplang for breakfast).

    Now with string interpolation the intended code would look like this:

    public static string ZeroPadString(string _value, int _length) => $"{_value}:D10";
    
    

    However this would be very bad practice for one simple reason: To get the most out of string interpolation, you want to construct the whole string in one go, here would be an example:

    var name = $"{firstName} {lastName}";
    // Bunch of code
    var message = $"Dear customer {name}, The total amount of your {amount:D3} ordered items from {orderedAt:yyyy-MM-dd} will be {total:N2} schillings. Your invoice ID is '{uuid:N}'.";
    

    Now reasonable assumption of a translation is that those two lines get translated to:

    var name = string.Concat(firstName, " ", lastName);
    // Bunch of code
    var message = string.Format("Dear customer {0}, The total amount of your {1:D3} ordered items from {2:yyyy-MM-dd} will be {3:N2} schillings. Your invoice ID is '{4:N}'.", name, amount, orderedAt, total, uuid);
    

    Now potentially the second line will actually not use the old string.Format method, because with code generation a template could be constructed to avoid the parsing the format string instead, so there is another reason not to use those methods directly when you absolutely not know what your are actually doing. Compared to Java development in C# moves quickly and what was a pattern just one year ago can be an anti-pattern a year later (a good example is 'init' before and after 'required' in combination with null bangs).

    Addendum 2024-10-01 02:02: I just checked, the current version of .net uses DefaultInterpolatedStringHandler instead of the legacy string.Format version, but not codegen yet.

  • LZ79LRU (unregistered)

    Oh come on. I wrote a beautiful algorithm for this and it's stuck on "approval". I wish they'd just disable the stupid thing. All it does is block honest people posting.

  • (nodebb)

    So many missing returns! But not 81 of them...

  • teenadultclasses (unregistered)

    "Thank you for this thoughtful post! I truly appreciate how you’ve captured the journey of blogging over the years. It’s inspiring to reflect on the past while looking ahead to the future possibilities. Your insights have given me a lot to think about—keep up the great work!"

  • teenadultclasses (unregistered)

    "Thank you for this thoughtful post! I truly appreciate how you’ve captured the journey of blogging over the years. It’s inspiring to reflect on the past while looking ahead to the future possibilities. Your insights have given me a lot to think about—keep up the great work!"

Leave a comment on “Switch How We Do Padding”

Log In or post as a guest

Replying to comment #:

« Return to Article