Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mask string?

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

like image 585
mko Avatar asked Mar 14 '12 16:03

mko


People also ask

How do you mask a string in Java?

Create a new string with StringBuilder, copy over first 4 characters. Then loop until length of the string and mask them with a * character.

What is string mask?

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.

What is mask in Java?

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.


2 Answers

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);
    }
}
like image 67
ESipalis Avatar answered Sep 28 '22 08:09

ESipalis


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...

like image 36
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet