Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Basic String Compression in C
#include <stdio.h> int main() { // Declaring the variable for storing the string and a single character. char str[1000], x; // Variable for the compressed string. char compress[strlen(str)]; // 'i' variable for the loop, 'count' counter for a character, // 'index' for storing the current index we are at in the 'compress' string. int i, count = 1, index = 0; printf("Enter a string: "); // Printing a message gets(str); // Getting the input. x = str[0]; for (i = 1; i <= strlen(str); i++) { // Here we are delcaring a string for storing the number as a string, just in case, // the number is more than a single-digit number. char number_string[10]; int j; if ((int)str[i] == (int)x) count++; // Counting the character. else { compress[index++] = (char)x; // Adding the previous character and increasing the index by one. // Checking if the count of the character is more than one, // or else it will unncessarily bloat the previous string which is what we are trying not to do. if (count > 1) { // Converting the count of the previous character to string in order to store // it in the Compressed String digit by digit. sprintf(number_string, "%d", count); for (j = 0; j < strlen(number_string); j++) { compress[index++] = number_string[j]; } } x = str[i]; count = 1; } } // Printing the string. printf("Compressed String: %s", compress); return 0; } // PROGRAM BY 'JAMES COLLINS'
run
|
edit
|
history
|
help
1
strcat
Binary to Integer (C)
dcl
4
Is const really const? Yes
Project 3 part 2 Book v0.5
18BCE2182 ASSESS_1 Q1-4
3.1.2 Matrix add/sub file concept
Hello world.c
intro coding hello world