Fill string with zeros [duplicate]

3

How to check and fill a string if its size is less than a condition? For example, I always need to have a string size of 8 or 9. If the string is larger I give a substring by taking only the first 9 characters. If it is smaller, I need to fill in the "0" zeros on the left. Example: '988554' should be '000988554'. Important is to keep in the 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"
                        }
    
asked by anonymous 12.04.2018 / 16:41

3 answers

5

I could do it this way:

string a="988554";

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

Return would be: 00988554

    
12.04.2018 / 16:51
3

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

Always look for ready-made functions. Unless it does not solve your problem, it is best because it has already been tested.

using static System.Console;

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

See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .

    
12.04.2018 / 16:52
2

It could look like this:

int tamanhoFinal = 9;
int numero = 988554;


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

link

    
12.04.2018 / 16:49