关于一道面试题,使用C#实现字符串反转算法
时间:2011-04-07 来源:JunjieChang
public static string Reverse(string str)
{ if (string.IsNullOrEmpty(str)) { throw new ArgumentException("参数不合法"); }
StringBuilder sb = new StringBuilder(str.Length);
for (int index = str.Length - 1; index >= 0; index--)
{ sb.Append(str[index]); }
return sb.ToString();
}
public static string Reverse(string str)
{ if (string.IsNullOrEmpty(str)) { throw new ArgumentException("参数不合法"); }
char[] chars = str.ToCharArray();
int begin = 0; int end = chars.Length - 1; char tempChar;
while (begin < end)
{ tempChar = chars[begin]; chars[begin] = chars[end]; chars[end] = tempChar; begin++; end--; }
string strResult = new string(chars);
return strResult;
}