English 中文(简体)
我如何优化这个格式账户数方法?
原标题:How do I optimize this FormatAccountNumber method?
  • 时间:2012-05-24 14:02:57
  •  标签:
  • c#

我写了这个格式化账号的方法 :

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();
    }
}

使用 < code> StringBuilder 来优化它还是已经优化了?

最佳回答

下面的方法可以做你需要的事,很容易读,执行速度要快好几倍。即使不需要执行数千次,您也想看到执行时间的差。

    public static string FormatAccountNumber2(string accountNumber)
    {
        if (string.IsNullOrEmpty(accountNumber))
            return string.Empty;

        if (accountNumber.Length < 4)
            return "****";

        return new string( * , accountNumber.Length - 4) +
            accountNumber.Substring(accountNumber.Length - 4);
    }
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签