📜  如何在C#中用前导零填充整数?

📅  最后修改于: 2021-05-29 21:52:31             🧑  作者: Mango

给定数字N ,任务是用C#中的P个前导零填充该数字。

例子:

Input: N = 123 , P = 4
Output: 0123
  
Input: N = -3 , P = 5
Output: -00003

方法1:使用字符串Format()方法  Format()方法用于将指定字符串中的一个或多个格式项替换为指定对象的字符串表示形式

例子 :

C#
val = string.Format("{0:0000}", N);


C#
// C# program to pad an integer
// number with leading zeros
using System;
  
class GFG{
      
    // Function to pad an integer number 
    // with leading zeros
    static string pad_an_int(int N, int P)
    {
        // string used in Format() method
        string s = "{0:";
        for( int i=0 ; i


C#
// C# program to pad an integer
// number with leading zeros
using System;
  
public class GFG{
      
    // Function to pad an integer number 
    // with leading zeros
    static string pad_an_int(int N, int P)
    {
        // string used in ToString() method
        string s = "";
        for( int i=0 ; i


输出:

// C# program to pad an integer
// number with leading zeros
using System;
  
public class GFG{
      
    // Function to pad an integer number 
    // with leading zeros
    static string pad_an_int(int N, int P)
    {
        // use of ToString() method
        string value = N.ToString();
          
        // use of the PadLeft() method
        string pad_str = value.PadLeft(P, '0');
          
        // return output
        return pad_str;
    }
      
    // driver code
    public static void Main(string[] args)
    {
        int N = 123; // Number to be pad
        int P = 5; // Number of leading zeros
          
        Console.WriteLine("Before Padding: " + N);
          
        // Function calling
        Console.WriteLine("After Padding: " + pad_an_int(N, P));
    }
}

方法2:使用ToString ()方法  ToString ()方法用于将当前实例的数值转换为其等效的字符串表示形式。

例子 :

C#

Before Padding: 123
After Padding: 00123

输出:

val = N.ToString("0000");

方法3:使用PadLeft ()方法  PadLeft ()方法用于通过填充字符来使String中的字符右对齐。

例子 :

C#

// C# program to pad an integer
// number with leading zeros
using System;
  
public class GFG{
      
    // Function to pad an integer number 
    // with leading zeros
    static string pad_an_int(int N, int P)
    {
        // string used in ToString() method
        string s = "";
        for( int i=0 ; i

输出:

Before Padding: 123
After Padding: 00123