[原]字符串反转
- 使用栈
public static string ReverseByStack(this string original) { Stack<char> stack = new Stack<char>(); foreach (char ch in original) { stack.Push(ch); } char[] c = new char[original.Length]; for (int i = 0; i < original.Length; i++) { c[i] = stack.Pop(); } return new string(c); }
- 使用XOR
public static string ReverseByXor(this string original) { char[] charArray = original.ToCharArray(); int l = original.Length - 1; for (int i = 0; i < l; i++, l--) { charArray[i] ^= charArray[l]; charArray[l] ^= charArray[i]; charArray[i] ^= charArray[l]; } return new string(charArray); }
- 使用指针
public static unsafe string ReverseByPointer(this string original) { fixed (char* pText = original) { char* pStart = pText; char* pEnd = pText + original.Length - 1; for (int i = original.Length / 2; i >= 0; i--) { char temp = *pStart; *pStart++ = *pEnd; *pEnd-- = temp; } return original; } }
作者:wjh200821 发表于2012-4-23 12:52:49 原文链接
阅读:7 评论:0 查看评论
posted on 2012-04-23 12:53 tilltheendwjx 阅读(159) 评论(0) 编辑 收藏 举报