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

时间:2022-05-25 18:15:38

本文实例为大家分享了C#字符串倒序写法的实现代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//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;
}
 
// Array.Reverse function
public string ReverseB(string text)
{
  char[] charArray = text.ToCharArray();
  Array.Reverse(charArray);
  return new string(charArray);
}
 
// 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();
}
 
// LINQ
public string ReverseD(string text)
{
  return new string(text.ToCharArray().Reverse().ToArray());
}
 
// 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();
}

以上就是本文的全部内容,希望对大家学习C#程序设计有所帮助。