Last active
November 5, 2018 12:36
-
-
Save chrisfcarroll/93eaf40f39cd3c83cc49790c718dde37 to your computer and use it in GitHub Desktop.
String.Masked() extension method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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