码迷,mamicode.com
首页 > Windows程序 > 详细

【转】c#实现字符串倒序的n种写法

时间:2015-09-11 23:29:04      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

其中LINQ写法最为简洁

//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#实现字符串倒序的n种写法

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/4802306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!