Apply mask to a string

后端 未结 2 520
夕颜
夕颜 2021-01-18 02:42

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

相关标签:
2条回答
  • 2021-01-18 03:12

    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;
    
    0 讨论(0)
  • 2021-01-18 03:21

    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();
    }
    
    0 讨论(0)
提交回复
热议问题