方法1:
使用string.PadRight()
方法2:
自定义一个字符串补齐的静态方法:
public static string PadRight(string src, char c, Int32 totalLength)
{
if (totalLength < src.Length)
return src;
return src + new String(c, totalLength - src.Length);
}
使用第二种方法效率更高。
测试结果代码如下:
using System;
using System.Collections.Generic;
using System.Diagnostics;
public class MyClass
{
public static void RunSnippet()
{
Stopwatch s1=new Stopwatch();
string s="1",s2="";
int recurring=1000000;
int recurringChar=20;
s1.Start();
for(int i=1;i<recurring;i++){
s2=PadRight(s,'0',recurringChar);
}
s1.Stop();
WL("静态方法:PadRight耗时:{0}",s1.ElapsedMilliseconds.ToString());
s1.Reset();
s="";
s2="";
s1.Start();
for(int i=1;i<recurring;i++){
s2=s.PadRight(recurringChar,'0');
}
s1.Stop();
WL("string.PadRight()耗时:{0}",s1.ElapsedMilliseconds.ToString());
s1.Reset();
}
public static string PadRight(string src, char c, Int32 totalLength)
{
if (totalLength < src.Length)
return src;
return src + new String(c, totalLength - src.Length);
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
#endregion
}