I’ve written this method for formatting Account number:
public static string FormatAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
return string.Empty;
if (accountNumber.Length < 4)
return "****";
else
{
StringBuilder stringBuilder = new StringBuilder();
int starLength = accountNumber.Length - 4;
for (int index = 0; index < starLength; index++)
stringBuilder.Append("*");
stringBuilder.Append(accountNumber.Substring(accountNumber.Length - 4));
return stringBuilder.ToString();
}
}
Can this optimized or is it already optimized by use of StringBuilder?
Method below does what you need, is easy to read and executes several times faster. Still if you don’t need to execute it thousands times, you want see the execution time difference.