Fill string with zeros

Asked

Viewed 8,240 times

3

How to check and fill in a string if its size is less than one condition? For example, I always need to have a string in the size of 8 or 9. If the string is longer I give a substring taking only the first 9 characters. If she’s a minor, I need to fill in "0" zeros on the left. Example : '988554' should be '000988554'. Important to keep in string format and not convert.

int TamanhoDaString= Regex.Replace(minhaString, "[^0-9]", "").Length; //ex: tamanho 5
                   int QuantDeZero = 9 - TamanhoDaString; // resultado = 4
                   int i;
                   string zeros = "0";



                 for (i = 1; i < QuantDeZero; i++)
                       {
                              // aqui engatei, pois como vou concatenar uma string com inteiro?
//resultado teria que ser zeros = "0000"
                        }
  • Have you tried numero.ToString().PadLeft(9, '0') ?

3 answers

7


You could do it that way:

string a="988554";

a = a.PadLeft(8, '0');

Return would be: 00988554

  • Thank you. That’s right

  • if it helped just mark as solved

  • If downvoter can explain down ? it solves the problem with a ready c function#

  • You’re right, you’ll understand these people.

  • Normal hehehehe

5

Use the PadLeft(). Pass how many characters to string should have in total and which character wants it to be placed, the default is a blank.

Always look for ready-made functions. Unless you don’t solve your problem it’s better because it’s been tested.

using static System.Console;

class Program {
    static void Main() {
        WriteLine("988554".PadLeft(8, '0'));
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • 1

    That there boss without reinventing the wheel

  • 1

    blz, I didn’t. Getting to c# a little while ago. Thanks

2

It could be so:

int tamanhoFinal = 9;
int numero = 988554;


Console.WriteLine(numero.ToString("D" + tamanhoFinal.ToString()));

https://dotnetfiddle.net/5I69S4

  • opa.. That’s right. But I could explain ?

  • D specifies the Decimal value. Source: https://docs.microsoft.com/pt-br/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

Browser other questions tagged

You are not signed in. Login or sign up in order to post.