CShap 字符串压缩 源代码
时间: 2023-09-14 12:08:40 浏览: 144
以下是一个C#字符串压缩的示例代码:
```csharp
public static string Compress(string uncompressed)
{
byte[] data = Encoding.UTF8.GetBytes(uncompressed);
using (MemoryStream outputStream = new MemoryStream())
{
using (DeflateStream compressionStream = new DeflateStream(outputStream, CompressionMode.Compress))
{
compressionStream.Write(data, 0, data.Length);
}
return Convert.ToBase64String(outputStream.ToArray());
}
}
public static string Decompress(string compressed)
{
byte[] data = Convert.FromBase64String(compressed);
using (MemoryStream inputStream = new MemoryStream(data))
{
using (MemoryStream outputStream = new MemoryStream())
{
using (DeflateStream decompressionStream = new DeflateStream(inputStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(outputStream);
}
return Encoding.UTF8.GetString(outputStream.ToArray());
}
}
}
```
这个示例使用了C#的标准库中的DeflateStream类来进行压缩和解压缩。压缩的过程是将字符串转换成字节数组,然后使用DeflateStream进行压缩并转换成Base64字符串。解压缩的过程是将Base64字符串转换成字节数组,然后使用DeflateStream进行解压缩并转换成字符串。
阅读全文