我刚刚在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;
}

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


当前回答

在使用StringInfo.GetTextElementEnumerator()的地方有几个正确答案。向你致敬!

现在,让我们找出最有效的方法来使用这个方法。首先,大多数答案涉及调用Reverse()和ToArray(),这在热路径上是一个大禁忌。为了获得最佳性能,我们希望避免分配垃圾。例如,临时字符串,分配器,数组等。

优化的管柱反转

降低气相色谱压力。也就是说,没有LINQ枚举器,没有数组。 使用跨 使用String.Create ()

using System.Globalization;

public static class StringExtensions
{
    public static string AsReversed(this string s)
    {
        return string.Create(s.Length, s, (chars, state) =>
        {
            int i = 0;
            var enumerator = StringInfo.GetTextElementEnumerator(s);
            while (enumerator.MoveNext())
            {
                var element = enumerator.GetTextElement();
                i += element.Length;
                element.CopyTo(chars[^i..]);
            }
        });
    }
}

请注意,GetTextElementEnumerator() API在. net Core 3.1和更早的版本中包含一个错误。确保运行。net 5或更高版本!最后,请务必查看正在讨论API改进的问题#19423。

其他回答

string A = null;
//a now is reversed and you can use it
A = SimulateStrReverse.StrReverse("your string");

public static class SimulateStrReverse
{
    public static string StrReverse(string expression)
    {
        if (string.IsNullOrEmpty(expression))
            return string.Empty;

        string reversedString = string.Empty;
        for (int charIndex = expression.Length - 1; charIndex >= 0; charIndex--)
        {
            reversedString += expression[charIndex];
        }
        return reversedString;
    }
}

看看维基百科的条目。它们实现了字符串。反向扩展法。这允许你编写这样的代码:

string s = "olleh";
s.Reverse();

他们还使用ToCharArray/Reverse组合,这是这个问题的其他答案所建议的。源代码如下所示:

public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}

“更好的方式”取决于在你的情况下什么对你更重要,性能、优雅性、可维护性等等。

总之,这里有一个使用数组的方法。相反:

string inputString="The quick brown fox jumps over the lazy dog.";
char[] charArray = inputString.ToCharArray(); 
Array.Reverse(charArray); 

string reversed = new string(charArray);

简单而漂亮的答案是使用扩展方法:

static class ExtentionMethodCollection
{
    public static string Inverse(this string @base)
    {
        return new string(@base.Reverse().ToArray());
    }
}

这是输出:

string Answer = "12345".Inverse(); // = "54321"

我在面试中也被问到类似的问题。这是我的回答,尽管它在性能上可能没有其他答案那么快。我的问题是“创建一个类,它可以有一个反向打印字符串的方法”:

using System;
using System.Collections.Generic;
using System.Linq;

namespace BackwardsTest
{
    class PrintBackwards
    {
        public static void print(string param)
        {
            if (param == null || param.Length == 0)
            {
                Console.WriteLine("string is null");
                return;
            }
            List<char> list = new List<char>();
            string returned = null;
            foreach(char d in param)
            {
                list.Add(d);
            }
            for(int i = list.Count(); i > 0; i--)
            {
                returned = returned + list[list.Count - 1];
                list.RemoveAt(list.Count - 1);
            }
            Console.WriteLine(returned);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string test = "I want to print backwards";
            PrintBackwards.print(test);
            System.Threading.Thread.Sleep(5000);
        }
    }
}