8

I am reading a string ID value from a table. When the ID was input by the user, it was done with an input mask that the user defined, so the mask could have been something like 000-00-0000, ##-######, AA-9999999, etc. The mask will vary by user, and so must be evaluated at runtime.

Given that only the alphanumeric text is stored in the table, what is the best way of generating a new string with that mask applied?

For example:

Table value = "123456789"

If user has defined mask of 000-00-0000, I want to get string 123-45-6789.

If user has defined mask of AA-9999999, I want to get string 12-3456789.

If user has defined mask of FR999_999999, I want to get string FR123_456789.

AlexB
  • 7,302
  • 12
  • 56
  • 74
PahJoker
  • 159
  • 2
  • 4
  • 13

2 Answers2

7

It seems like the mask pattern is that it will insert matching dashes for every dash in the mask. If that's the case then this should work.

public static string MaskValue(string mask, string value) {
  var builder = new System.Text.StringBuilder();
  var maskIndex = 0;
  var valueIndex = 0;
  while (maskIndex < mask.Length && valueIndex < value.Length) {
    if (mask[maskIndex] == '-') {
      builder.Append('-');
      maskIndex++;
    } else {
      builder.Append(value[valueIndex]);
      maskIndex++;
      valueIndex++;
    }
  }

  // Add in the remainder of the value
  if (valueIndex + 1 < value.Length) {
    builder.Append(value.Substring(valueIndex);
  }

  return builder.ToString();
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Good interpretation of the problem. I wasn't quite sure what he wanted. Note typo: `max.Length` in your while loop. – Joel Lee Apr 01 '11 at 04:39
  • Dashes are the most likely scenario, but not the only possibility. Please see edited question above, which now includes example of a mask with two leading characters and an underscore. – PahJoker Apr 04 '11 at 03:15
0

This does exactly what I need. The only downside is that it ties me to the Windows Forms assembly.

        MaskedTextBox mtb = new MaskedTextBox("FR999_999999");
        mtb.Text = "123456789";
        return mtb.Text;
PahJoker
  • 159
  • 2
  • 4
  • 13