我刚刚在c# 2.0中写了一个字符串反向函数(即LINQ不可用),然后想到了这个:

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

就我个人而言,我并不喜欢这个功能,我相信有更好的方法来实现它。是吗?


当前回答

使用LINQ的聚合函数

string s = "Karthik U";
s = s.Aggregate(new StringBuilder(), (o, p) => o.Insert(0, p)).ToString();

其他回答

如果在面试中你被告知不能使用Array。反过来,我想这可能是最快的一个。它不会创建新的字符串,只迭代数组的一半以上(即O(n/2)次迭代)

    public static string ReverseString(string stringToReverse)
    {
        char[] charArray = stringToReverse.ToCharArray();
        int len = charArray.Length-1;
        int mid = len / 2;

        for (int i = 0; i < mid; i++)
        {
            char tmp = charArray[i];
            charArray[i] = charArray[len - i];
            charArray[len - i] = tmp;
        }
        return new string(charArray);
    }
public static string Reverse(string input)
{
    return string.Concat(Enumerable.Reverse(input));
}

当然,您可以使用Reverse方法扩展字符串类

public static class StringExtensions
{
    public static string Reverse(this string input)
    {
        return string.Concat(Enumerable.Reverse(input));
    }
}

Greg Beech发布了一个不安全的选项,它确实很快(这是一个原地逆转);但是,正如他在回答中指出的那样,这完全是一个灾难性的想法。

也就是说,我很惊讶有这么多的共识,Array。逆向是最快的方法。仍然有一种不安全的方法,它返回字符串的反向副本(没有原地反转的恶作剧),比Array快得多。小字符串的反向方法:

public static unsafe string Reverse(string text)
{
    int len = text.Length;

    // Why allocate a char[] array on the heap when you won't use it
    // outside of this method? Use the stack.
    char* reversed = stackalloc char[len];

    // Avoid bounds-checking performance penalties.
    fixed (char* str = text)
    {
        int i = 0;
        int j = i + len - 1;
        while (i < len)
        {
            reversed[i++] = str[j--];
        }
    }

    // Need to use this overload for the System.String constructor
    // as providing just the char* pointer could result in garbage
    // at the end of the string (no guarantee of null terminator).
    return new string(reversed, 0, len);
}

以下是一些基准测试结果。

您可以看到,相对于Array,性能增益会缩小,然后消失。当字符串变大时,反向方法。然而,对于小型到中型的字符串,很难击败这种方法。

不要为函数而烦恼,只要在适当的地方做就可以了。注意:第二行会在一些VS版本的即时窗口中抛出一个参数异常。

string s = "Blah";
s = new string(s.ToCharArray().Reverse().ToArray()); 
     using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {     
        public static string ReverseString(string str)
        {
            int totalLength = str.Length;
            int iCount = 0;
            string strRev = string.Empty;
            iCount = totalLength;
            while (iCount != 0)
            {
                iCount--;
                strRev += str[iCount]; 
            }
            return strRev;
        }
        static void Main(string[] args)
        {
            string str = "Punit Pandya";
            string strResult = ReverseString(str);
            Console.WriteLine(strResult);
            Console.ReadLine();
        }
    }

  }