c# - 一种使用独特压缩形式解压缩文本文件的更快方法

标签 c# compression run-length-encoding

我不知道这种类型的压缩是否在其他地方使用,但这就是它的工作原理。它使用 4 个字符。第一个字符“ú”表示紧随其后的是压缩。接下来的 2 个字符以十六进制表示第 4 个位置要重复多少个。例如:

22ú05hú0C0AFC001

会是:

22hhhhh000000000000AFC001

我能够做到这一点,但它运行得非常慢。一个 20k 的文件可能需要 5 分钟或更长时间。

这是我的代码:

public string doDecompression(string Content)
{
    string pattern = @"ú...";
    Regex rgx = new Regex(pattern);

    foreach (Match match in rgx.Matches(Content))
    {
        // Gets the raw Hex code
        string hex = match.ToString().Substring(1, 2);

        // Converts Hex code to an Integer 
        int convertedHex = Int32.Parse(hex, NumberStyles.HexNumber);

        // Gets the character to repeat
        string character = match.ToString().Substring(3, 1);

        // Converts the character to repeat into
        // a "char" so I can use it in the line below
        char repeatingChar = character[0];

        // Creates a string out of the repeating characters 
        string result = new String(repeatingChar, convertedHex);

        // This does the actual replacing of the text
        Content = Content.Replace(match.ToString(), result); 
    }

    return Content;
}

有没有更好的办法?

最佳答案

您在这里看到的是 RLE algorithm 的变体。 .

你真的不需要正则表达式来完成这项工作,更不用说使用不可变字符串进行昂贵的操作了。

尝试以下方法:

public static IEnumerable<char> Decompress(string compressed)
{
    for(var i = 0; i < compressed.Length; )
    {
        var c = compressed[i++];
        if(c == 'ú')
        {
            var count = int.Parse(compressed.Substring(i, 2), NumberStyles.HexNumber);
            i += 2;

            c = compressed[i++];

            foreach(var character in Enumerable.Repeat(c, count))
                yield return character;
        }
        else
        {
            yield return c;
        }
    }
}

关于c# - 一种使用独特压缩形式解压缩文本文件的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29758100/

相关文章:

java - FTP下载的文件,解压时出错

r - 使用dplyr时使用rle按运行分组

matlab - Matlab 中的运行长度编码

python - Python 中的 R group_by() + rleid() 等效项

c# - 我可以在不引用类型的情况下反序列化泛型吗?

c# - 尝试使用 sqlite-net 按 PrimaryKey 选择时,SQLite 没有结果

delphi - Delphi 2009 中的 Zlib

c# - 在源代码级别运行的 C# 静态源代码分析

c# - 多表同款

java - 通过套接字发送压缩数据