您好,登錄后才能下訂單哦!
在C語言中,字符串的壓縮和解壓通常使用第三方庫來實(shí)現(xiàn),如zlib
sudo apt-get install zlib1g-dev
compress_decompress.c
的文件,并添加以下代碼:#include<stdio.h>
#include<string.h>
#include <zlib.h>
// 壓縮函數(shù)
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;
}
// 解壓縮函數(shù)
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
然后運(yùn)行生成的可執(zhí)行文件:
./compress_decompress
輸出結(jié)果應(yīng)該類似于:
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語言中對字符串進(jìn)行壓縮和解壓。請注意,這個示例僅適用于簡單的字符串,對于大型數(shù)據(jù)集,你可能需要調(diào)整緩沖區(qū)大小和壓縮/解壓縮函數(shù)以獲得更好的性能。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。