Jeffnl
Jeffnl

Reputation: 261

Fill string with four digits

I need to format a string to four characters, i get data from 0 to 4 characters, all the characters that are not filled must be filled with 'F' to the left, example:

string Data = "1T1";
//do somthing
Data = "F1T1";

or

string Data = "X";
//do somthing
Data = "FFFX";

Upvotes: 1

Views: 338

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98760

You can use a method like;

static void Main(string[] args)
{
    Console.WriteLine(AddF("11"));
    Console.WriteLine(AddF("1T1"));
    Console.WriteLine(AddF("X"));
}

static string AddF(string s)
{
    if (s.Length < 4)
        s = s.PadLeft(4, 'F');
    return s
}

Output will be;

FF11
F1T1
FFFX

HERE a DEMO.

String.PadLeft

Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

Upvotes: 2

VikciaR
VikciaR

Reputation: 3412

String.PadLeft

string str = "forty-two";
char pad = '.';

Console.WriteLine(str.PadLeft(15, pad));    // Displays "......forty-two".
Console.WriteLine(str.PadLeft(2, pad));     // Displays "forty-two".

Upvotes: 2

Rajeev Kumar
Rajeev Kumar

Reputation: 4963

You can do this by PadLeft

Data.PadLeft(4,'F');

Upvotes: 4

cuongle
cuongle

Reputation: 75306

Sound like you need PadLeft method:

Data = Data.PadLeft(4, 'F');

Upvotes: 3

Related Questions