I have a string with value "1131200001103".
How can I display it as a string in this format "11-312-001103" using Response.Write(value)?
Thanks
Create a new string with StringBuilder, copy over first 4 characters. Then loop until length of the string and mask them with a * character.
The mask may be alphabetic, numeric or contain blank characters or any of the special characters valid within a string name. For an inclusive mask the string is accepted for further processing; for an exclusive mask the string is rejected. A selection mask table is used to store more than one mask.
Masked types are a new typestate mechanism that explicitly tracks the initialization state of objects and prevents reading from uninitialized fields. They even work in the presence of cyclic data structures and inheritance.
I wrote a quick extension method for same / similar purpose (similar in a sense that there's no way to skip characters).
Usage:
var testString = "12345";
var maskedString = testString.Mask("##.## #"); // 12.34 5
Method:
public static string Mask(this string value, string mask, char substituteChar = '#')
{
int valueIndex = 0;
try
{
return new string(mask.Select(maskChar => maskChar == substituteChar ? value[valueIndex++] : maskChar).ToArray());
}
catch (IndexOutOfRangeException e)
{
throw new Exception("Value too short to substitute all substitute characters in the mask", e);
}
}
Any reason you don't want to just use Substring
?
string dashed = text.Substring(0, 2) + "-" +
text.Substring(2, 3) + "-" +
text.Substring(7);
Or:
string dashed = string.Format("{0}-{1}-{2}", text.Substring(0, 2),
text.Substring(2, 3), text.Substring(7));
(I'm assuming it's deliberate that you've missed out two of the 0s? It's not clear which 0s, admittedly...)
Obviously you should validate that the string is the right length first...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With