mask all digits except first 6 and last 4 digits of a string( length varies )

前端 未结 9 834
无人及你
无人及你 2021-01-01 14:26

I have a card number as a string, for example:

string  ClsCommon.str_CardNumbe r = \"3456123434561234\";

The length of this card number can

9条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 14:43

    Possible implementation (acccepts varios formats e.g. numbers can be divided into groups etc.):

    private static String MaskedNumber(String source) {
      StringBuilder sb = new StringBuilder(source);
    
      const int skipLeft = 6;
      const int skipRight = 4;
    
      int left = -1;
    
      for (int i = 0, c = 0; i < sb.Length; ++i) {
        if (Char.IsDigit(sb[i])) {
          c += 1;
    
          if (c > skipLeft) {
            left = i;
    
            break;
          }
        }
      }
    
      for (int i = sb.Length - 1, c = 0; i >= left; --i)
        if (Char.IsDigit(sb[i])) {
          c += 1;
    
          if (c > skipRight)
            sb[i] = 'X';
        }
    
      return sb.ToString();
    }
    
    // Tests 
    
      // 3456-12XX-XXXX-1234
      Console.Write(MaskedNumber("3456-1234-3456-1234"));
      // 3456123XXXXX1234
      Console.Write(MaskedNumber("3456123434561234"));
    

    this implementation just masks the digits and preserve the format.

提交回复
热议问题