Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
String.Masked() extension method
public static class StringExtensions
{
/// <summary>
/// Overwrite the right-most fraction 1/<paramref name="maskFractionOneOver"/> of <paramref name="str"/> with <paramref name="maskCharacter"/>
/// </summary>
/// <param name="str"></param>
/// <param name="maskFractionOneOver"></param>
/// <param name="maskCharacter"></param>
/// <example>"1234".Masked() => "123*"</example>
/// <returns>the masked string</returns>
public static string Masked(this string str, int maskFractionOneOver = 5, char maskCharacter = '*')
{
if (string.IsNullOrEmpty(str)) return str;
maskFractionOneOver = Math.Max(maskFractionOneOver, 1);
int fraction = (maskFractionOneOver-1) * str.Length / maskFractionOneOver;
return str.Substring(0,fraction) .PadRight(str.Length, maskCharacter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.