您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C语言中,字符串的压缩和解压通常使用第三方库来实现,如zlib
sudo apt-get install zlib1g-dev
compress_decompress.c
的文件,并添加以下代码:#include<stdio.h>
#include<string.h>
#include <zlib.h>
// 压缩函数
int compress_string(const char *input, char *output, int output_size) {
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = strlen(input) + 1;
stream.next_in = (Bytef *)input;
stream.avail_out = output_size;
stream.next_out = (Bytef *)output;
deflateInit(&stream, Z_DEFAULT_COMPRESSION);
deflate(&stream, Z_FINISH);
deflateEnd(&stream);
return stream.total_out;
}
// 解压缩函数
int decompress_string(const char *input, char *output, int output_size) {
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = strlen(input) + 1;
stream.next_in = (Bytef *)input;
stream.avail_out = output_size;
stream.next_out = (Bytef *)output;
inflateInit(&stream);
inflate(&stream, Z_NO_FLUSH);
inflateEnd(&stream);
return stream.total_out;
}
int main() {
const char *input_str = "Hello, World!";
char compressed_str[100];
char decompressed_str[100];
int compressed_size = compress_string(input_str, compressed_str, sizeof(compressed_str));
printf("Compressed string: ");
for (int i = 0; i < compressed_size; i++) {
printf("%02X ", (unsigned char)compressed_str[i]);
}
printf("\n");
int decompressed_size = decompress_string(compressed_str, decompressed_str, sizeof(decompressed_str));
decompressed_str[decompressed_size] = '\0';
printf("Decompressed string: %s\n", decompressed_str);
return 0;
}
gcc compress_decompress.c -o compress_decompress -lz
然后运行生成的可执行文件:
./compress_decompress
输出结果应该类似于:
Compressed string: 78 9C 4B CE CF 4D 55 48 2C 4A 2D 2E 4E 4F 4A 2C 4B 4C 4A 4D 4D 06 00 9D 4B 0C 00 00
Decompressed string: Hello, World!
这个示例展示了如何使用zlib库在C语言中对字符串进行压缩和解压。请注意,这个示例仅适用于简单的字符串,对于大型数据集,你可能需要调整缓冲区大小和压缩/解压缩函数以获得更好的性能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。