Basic String Compression
This program compresses string by counting consecutive characters.
Problem Statement
Write a Java program to compress "aaabbc" into "a3b2c1".
Source Code
| 1 | public class StringCompression { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq String Compression"); |
| 4 | String str="aaabbc"; |
| 5 | StringBuilder comp=new StringBuilder(); |
| 6 | int count=1; |
| 7 | for(int i=1;i<=str.length();i++){ |
| 8 | if(i==str.length() || str.charAt(i)!=str.charAt(i-1)){ |
| 9 | comp.append(str.charAt(i-1)).append(count); |
| 10 | count=1; |
| 11 | } else count++; |
| 12 | } |
| 13 | System.out.println("Compressed string: "+comp.toString()); |
| 14 | } |
| 15 | } |
Program Output
Eduinq String Compression Compressed string: a3b2c1
Explanation
Loop counts consecutive characters. - Compression appends character and count. - Together demonstrates basic string compression. Conclusion: Shows how to compress string using counts.