给定数字N ,任务是用C#中的P个前导零填充该数字。
例子:
Input: N = 123 , P = 4
Output: 0123
Input: N = -3 , P = 5
Output: -00003
方法1:使用字符串Format()方法 : Format()方法用于将指定字符串中的一个或多个格式项替换为指定对象的字符串表示形式。
Step 1: Get the Number N and number of leading zeros P.
Step 2: Convert the number to string and to pad the string, use the string.Format() method with the formatted string argument “{0:0000}” for P= 4.
Step 3: Return the padded string.
例子 :
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 ()方法用于将当前实例的数值转换为其等效的字符串表示形式。
Step 1: Get the Number N and number of leading zeros P.
Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4.
Step 3: Return the padded string.
例子 :
C#
Before Padding: 123
After Padding: 00123
输出:
val = N.ToString("0000");
方法3:使用PadLeft ()方法 : PadLeft ()方法用于通过填充字符来使String中的字符右对齐。
Step 1: Get the Number N and number of leading zeros P.
Step 2: Convert the number to string using the ToString() method.
val = N.ToString();
Step 3: Then pad the string by using the PadLeft() method.
pad_str = val.PadLeft(P, '0');
Step 4: Return the padded 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