C#实现字符串倒序的写法

1、for循环倒序排列字符

//string concatenation with for loop
public string ReverseA(string text)
{
  char[] cArray = text.ToCharArray();
  string reverse = String.Empty;
  for (int i = cArray.Length - 1; i > -1; i--)
  {
    reverse += cArray[i];
  }
  return reverse;
}

2、Reverse函数

// Array.Reverse function
public string ReverseB(string text)
{
  char[] charArray = text.ToCharArray();
  Array.Reverse(charArray);
  return new string(charArray);
}

3、Stack方法

// push/pop Stack<>
public string ReverseC(string text)
{
  Stack resultStack = new Stack();
  foreach (char c in text)
  {
    resultStack.Push(c);
  }

  StringBuilder sb = new StringBuilder();
  while (resultStack.Count > 0)
  {
    sb.Append(resultStack.Pop());
  }
  return sb.ToString();
}

4、LINQ

public string ReverseD(string text)
{
  return new string(text.ToCharArray().Reverse().ToArray());
}

5、StringBuilder

public string ReverseE(string text)
{
  char[] cArray = text.ToCharArray();
  StringBuilder reverse = new StringBuilder();
  for (int i = cArray.Length - 1; i > -1; i--)
  {
    reverse.Append(cArray[i]);
  }
  return reverse.ToString();
}
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花