| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <iostream> #include <string> #include <sstream> // Class for Run-Length Encoding (RLE) compression class RunLengthEncoder { public:     // Function to compress the input string using RLE     std::string compress(const std::string& input) {         if (input.empty()) return "";         std::ostringstream compressed;         char currentChar = input[0];         int count = 1;         for (size_t i = 1; i < input.size(); ++i) {             if (input[i] == currentChar) {                 ++count;             } else {                 compressed << currentChar << count;                 currentChar = input[i];                 count = 1;             }         }         compressed << currentChar << count; // Add the last run         return compressed.str();     }     // Function to decompress the RLE compressed string     std::string decompress(const std::string& compressed) {         std::ostringstream decompressed;         size_t i = 0;         while (i < compressed.size()) {             char currentChar = compressed[i++];             int count = 0;             while (i < compressed.size() && std::isdigit(compressed[i])) {                 count = count * 10 + (compressed[i++] - '0');             }             decompressed << std::string(count, currentChar);         }         return decompressed.str();     } }; int main() {     RunLengthEncoder rle;     std::string input;     std::cout << "Enter the string to compress: ";     std::getline(std::cin, input);     // Compress the input string     std::string compressed = rle.compress(input);     std::cout << "Compressed string: " << compressed << std::endl;     // Decompress the string     std::string decompressed = rle.decompress(compressed);     std::cout << "Decompressed string: " << decompressed << std::endl;     return 0; } | 
Explanation
- Class Definition (RunLengthEncoder):- Public Methods:
- compress(const std::string& input):- Compresses the input string using Run-Length Encoding (RLE).
- Iterates through the string, counting consecutive occurrences of each character.
- Constructs a compressed string in the format: character followed by the count.
- Returns the compressed string.
 
- decompress(const std::string& compressed):- Decompresses a string that was compressed using RLE.
- Parses the compressed string to reconstruct the original string.
- Returns the decompressed string.
 
 
 
- Public Methods:
- mainFunction:- Prompts the user to enter a string for compression.
- Uses the RunLengthEncoderclass to compress the input string and prints the result.
- Then decompresses the compressed string to verify the accuracy and prints the decompressed string.
 
