Je voudrais masquer une chaîne en utilisant différents paramètres comme le pourcentage de caractère à masquer, le caractère du masque et la position d'application du masque (Au début , au milieu ou à la fin de la chaîne). J'ai trouvé une solution mais je présume que ce n'est pas la meilleure solution. Ceci est mon code:Comment masquer une chaîne en utilisant différents paramètres de façon efficace et rapide
public static string MaskChars(this string value, char maskToApply = 'X', int percentToApply = 25, MaskOption maskOptions = MaskOption.InTheMiddleOfString)
{
string valueTrimmed = value.Trim();
int len = valueTrimmed.Length;
if (len == 0)
return Empty;
if (percentToApply >= 100)
return maskToApply.ToString(CultureInfo.InvariantCulture).Replicate(len);
var charsToMask = (int)Math.Round((decimal)(percentToApply * len)/100);
if (charsToMask == 0)
charsToMask = 1;
int top = len - charsToMask;
int maskCounter = 0;
var builder = new StringBuilder(len);
for (int i = 0; i < len; i++)
{
if (maskCounter < charsToMask)
{
switch (maskOptions)
{
// Apply mask in the middle of the string
case MaskOption.InTheMiddleOfString:
if (i >= charsToMask && i < top)
{
builder.Append(maskToApply);
maskCounter++;
}
break;
// Apply mask at the begining of the string
case MaskOption.AtTheBeginingOfString:
if (i < charsToMask)
{
builder.Append(maskToApply);
maskCounter++;
}
break;
// Apply mask at the end of the string
case MaskOption.AtTheEndOfString:
if (i >= top)
{
builder.Append(maskToApply);
maskCounter++;
}
break;
}
}
else
{
builder.Append(valueTrimmed[i]);
}
}
return builder.ToString();
}
où:
public enum MaskOption : byte
{
AtTheBeginingOfString = 1,
InTheMiddleOfString = 2,
AtTheEndOfString = 3
}
et Répliquer est une méthode simple pour reproduire une chaîne
public static string Replicate(this string value, int count)
{
if (IsNullOrEmpty(value))
return Empty;
if (count <= 0)
return value;
var builder = new StringBuilder();
builder.Append(value);
for (int i = count; i >= 1; i--)
builder.Append(value);
return builder.ToString();
}
Vous voudrez peut-être envisager d'afficher au [Code Review] (https://codereview.stackexchange.com/help/on-topic) au lieu. – CodeCaster
Si quelque chose ne fonctionne pas, veuillez décrire exactement le problème et le code qui ne fonctionne pas. –