反转字符串的最佳方法
问题描述:
我只需要在 C# 2.0 中编写一个字符串反向函数(即 LINQ 不可用)并想出了这个:
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:
public string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
就我个人而言,我对这个功能并不着迷,并且相信有更好的方法来做到这一点.有吗?
Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?
答
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}