如何修复stringBuilder以字符串和反向?

时间:2019-04-13 12:34:47

标签: c#

我有一个StringBuilder的结果,我想反转它,但是在C#中StringBuilder不支持.Reverse(),所以首先将其转换为string,然后我将其反转,并在字符串末尾添加“ $”。

但是答案是这样的:

System.Linq.Enumerable+<ReverseIterator>d__75`1[System.Char]"   string

我该如何解决?

StringBuilder result = new StringBuilder();
List<string> matrix = new List<string>();
List<int> indexes = new List<int>();
for (int i = 0; i < bwt.Length; i++)
{
    matrix.Add("" + bwt[i]);
    indexes.Add(i);
}
indexes.Sort((o1, o2) => matrix[o1].CompareTo(matrix[o2]));
int current = indexes[0];
for (int i = 0; i < bwt.Length - 1; i++)
{
    int index = indexes.IndexOf(current);
    string next = bwt[index].ToString();
    result.Append(next);
    current = index;
}
// return result.ToString().ToString() + "$";

2 个答案:

答案 0 :(得分:3)

StringBuilder允许您通过字符索引访问和操作字符。

string stringToReverse = "abcdefghijk";
var sb = new StringBuilder(stringToReverse);
for (int i = 0, j = sb.Length - 1; i < sb.Length / 2; i++, j--) {
    char temp = sb[i];
    sb[i] = sb[j];
    sb[j] = temp;
}
string reversed = sb.ToString();

但是我进行了一个测试,表明@Mendhak的版本更快。一百万次重复,字符串长度为100

StringBuilder: 974 ms
Mendhak:       209 ms

因此,在我的PC上,使用Mendhak的解决方案只需209 ns即可反转字符串。仅仅因为解决方案看起来更快,它一定不能更快。 Array.Reverse调用高度优化的外部方法private static extern bool TrySZReverse(Array array, int index, int count);

测试:

static class ReverseString
{
    const string stringToReverse = "abcdex.dfkjvhw4o5i8yd,vfjhe4iotuwyflkcjadhrlniqeuyfmln mclf8yuertoicer,tpoirsd,kfngoiw5r8t7ndlrgjhfg";

    public static string TestStringBuilder()
    {
        var sb = new StringBuilder(stringToReverse);
        for (int i = 0, j = sb.Length - 1; i < sb.Length / 2; i++, j--) {
            char temp = sb[i];
            sb[i] = sb[j];
            sb[j] = temp;
        }
        return sb.ToString();
    }

    // By Mendhak
    public static string TestArrayReverse()
    {
        char[] arr = stringToReverse.ToString().ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

    public static void Compare()
    {
        string result1 = TestStringBuilder();
        string result2 = TestArrayReverse();
        Console.WriteLine($"Are result1 and 2 equal?   {result1 == result2}");

        Measure("StringBuilder", TestStringBuilder);
        Measure("Array.Reverse", TestArrayReverse);
        Console.ReadKey();
    }

    public static void Measure(string method, Func<string> sut)
    {
        const int NTests = 1000000;

        var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (int i = 0; i < NTests; i++) {
            sut();
        }
        stopWatch.Stop();
        Console.WriteLine($"{method} = {stopWatch.ElapsedMilliseconds} ms");
    }
}

答案 1 :(得分:1)

您将需要采取一些额外的步骤来反转字符串。按照通常在stringbuilder(result)中进行构建,然后

char[] arr = result.ToString().ToCharArray();
Array.Reverse(arr);
return new string(arr) + "$";