Reputation: 6866
I have a string being passed to me which can be between 1 and 6 characters long. Depending on the length of the string I need to add the appropriate prefix to the start of the string and return the appeneded string. So if I have something like the following passed to me
I want the return string to look like
I have come up with the following method
public static string AddToStartOfString(string s)
{
string value = string.Empty;
switch (s.Length)
{
case 1:
value = "X00000" + s;
break;
case 2:
value = "X0000" + s;
break;
case 3:
value = "X000" + s;
break;
case 4:
value = "X00" + s;
break;
case 5:
value = "X0" + s;
break;
case 6:
value = "X" + s;
break;
}
return value;
}
This works. But I need this to work in case in future more lengths are added. Is there a way where I can add the prefix even if the length of string is greater than 6 in the future
Upvotes: 1
Views: 12366
Reputation: 412
had a similar problem recently, in your case i would do:
public static string Fill(string str, string prefix, int length)
{
for(int i=str.Length; i<length; i++)
str = "0" + str;
return prefix + str;
}
Upvotes: -1
Reputation: 3172
You can do this:
public static string AddToStartOfString(string s, int digitCount = 6)
{
return "X" + s.PadLeft(digitCount, '0');
}
Beware that an input string longer than the max number of digits, once transformed, will not be truncated and will be longer than for values in the correct range.
Upvotes: 4