帮我用c语言写一个字符串压缩
时间: 2023-06-01 20:03:09 浏览: 87
以下是一个使用基于计数的字符串压缩算法的C程序示例:
```
#include <stdio.h>
#include <string.h>
void compress(char *str) {
int len = strlen(str);
if (len == 0) return;
char last = str[0];
int count = 1;
int i, j;
for (i = 1, j = 0; i < len; i++) {
if (str[i] == last) {
count++;
} else {
str[j++] = last;
if (count > 1) {
char buffer[10];
sprintf(buffer, "%d", count);
int k;
for (k = 0; buffer[k]; k++) {
str[j++] = buffer[k];
}
}
last = str[i];
count = 1;
}
}
str[j++] = last;
if (count > 1) {
char buffer[10];
sprintf(buffer, "%d", count);
int k;
for (k = 0; buffer[k]; k++) {
str[j++] = buffer[k];
}
}
str[j] = '\0';
}
int main() {
char str[100];
printf("Enter a string to compress: ");
fgets(str, 100, stdin);
str[strcspn(str, "\n")] = '\0'; // remove newline character
compress(str);
printf("Compressed string: %s\n", str);
return 0;
}
```
该程序使用一个循环来遍历字符串中的每个字符,然后将相邻的重复字符计数,最终输出压缩后的字符串。例如,如果输入字符串为 "aaabbbbcccd",则输出为 "a3b4c3d1"。
阅读全文