1. 主页 > 用户投稿

字符串压缩c语言(用c语言实现字符串压缩)

嗯,就是将比较大的字符串进行压缩,使其占用空间小一点,我一般用在有时候接口间需要传输大量数据的时候(json数据较大或者含有base64),缩小体积以加快传输小效率。

实现功能:

压缩和解压字符串

开发环境:

开发工具: Visual Studio 2013

.NET Framework版本:4.5

实现代码:

string fileData = "", compress = ""; private void btnPath_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == DialogResult.OK) { textBox1.Text = ofd.FileName; FileInfo fi = new FileInfo(ofd.FileName); GetSize(fi.Length, lbFile); fileData = File.ReadAllText(ofd.FileName); } } private void btnCompress_Click(object sender, EventArgs e) { compress = Compress(fileData); GetSize(Encoding.Default.GetBytes(compress).Length, lbCompress); MessageBox.Show("成功"); } private void btnDecompress_Click(object sender, EventArgs e) { richTextBox1.Text = Decompress(compress); MessageBox.Show("成功"); } //压缩字符串 public string Compress(string value) { try { string data = ""; byte[] byteArray = Encoding.Default.GetBytes(value); using (MemoryStream ms = new MemoryStream()) { using (GZipStream sw = new GZipStream(ms, CompressionMode.Compress)) { sw.Write(byteArray, 0, byteArray.Length); GetSize(ms.Length, lbCompress); } data = Convert.ToBase64String(ms.ToArray()); } return data; } catch (Exception ex) { throw ex; } } //解压缩字符串 public string Decompress(string value) { try { string data = ""; byte[] bytes = Convert.FromBase64String(value); using (MemoryStream msReader = new MemoryStream()) { using (MemoryStream ms = new MemoryStream(bytes)) { using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress)) { byte[] buffer = new byte[1024]; int readLen = 0; while ((readLen = zip.Read(buffer, 0, buffer.Length)) > 0) { msReader.Write(buffer, 0, readLen); } } } data = Encoding.Default.GetString(msReader.ToArray()); } return data; } catch (Exception ex) { throw ex; } } //获取大小 private void GetSize(long size, Control control) { string sizeStr = ""; if (size < 1024) sizeStr = size.ToString("F2") + " Byte"; else if (size >= 1024 && size < 1048576) sizeStr = (size / 1024).ToString("F2") + " K"; else if (size >= 1048576 && size < 1073741824) sizeStr = (size / 1024 / 1024).ToString("F2") + " M"; else if (size >= 1073741824) sizeStr = (size / 1024 / 1024 / 1024).ToString("F2") + " G"; control.Text = sizeStr; }

实现效果:

以上就是爱惜日网»字符串压缩c语言(用c语言实现字符串压缩)的相关内容了,更多精彩请关注作者:爱惜日号SEO专员

声明:本文由爱惜日网/爱惜日号作者编辑发布,更多技术关注!

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 203304862@qq.com

本文链接:https://jinnalai.com/n/31686.html

联系我们

在线咨询:点击这里给我发消息

微信号:

工作日:9:30-18:30,节假日休息