您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。