【发布时间】:2013-04-30 20:10:43
【问题描述】:
我想操纵一种算法来压缩 C# 中的长字符串和短字符串,我尝试过的所有算法都能够压缩长字符串但不能压缩短字符串(大约 5 个字符)。代码是:
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Collections;
using System.Text;
namespace CompressString {
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>compressed string</returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.Default.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Encoding.Default.GetString(gzBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text</param>
/// <returns>uncompressed string</returns>
public static string DecompressString(string compressedText)
{
byte[] gzBuffer = Encoding.Default.GetBytes(compressedText);
using (MemoryStream ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.Default.GetString(buffer);
}
}
}}
我在以下行的解压缩方法中遇到了 InvalidDataException(解码时发现无效数据): zip.Read(buffer, 0, buffer.Length); 你有什么建议?
【问题讨论】:
-
你应该发布一些关于你尝试过的代码,或者至少扩展你的问题。见stackoverflow.com/faq
-
压缩不能永远保证让一切都更短......而且非常少量的数据压缩很少有效。
-
示例:如果您有一个类似
aaaaa的字符串,那么您可以将其缩短为类似5a的字符串。但是如果你有一个像afgdc这样的字符串,那么就没有真正有意义的方法来通过算法缩短它。您可以制作字典并说1 = "afgdc",然后只提交1,但对方需要知道1代表什么,因此您还需要提交字典,但您没有任何收获。 -
以某种方式将许多短字符串组合成1个长字符串,然后压缩。
-
我有一个最多 1200 个字符的字符串,我不应该将字符串压缩到哪个限制?
标签: c# compression