Question:
Write a Java program that reads in a sequence of characters of unknown length, compresses adjacent repeated characters, and prints the output to the screen. The program replaces strings of repeating character sequences by [nX] in the output, where n is an integer count of the number of repetitions , and X is the character.
A sample input and output session is given below:
A sample input and output session is given below:
Enter string: abbcccddddeeeeef a[2b][3c][4d][5e]f
Code:
import java.util.*; public class CompressString { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.print("Enter string: "); String str = sc.nextLine(); String tmp = ""; char d = ' '; int counter = 0; for(int i = 0; i < str.length(); i++){ counter = 0; for(int j = i; j < str.length(); j++){ if(str.charAt(i) == str.charAt(j)){ counter++; }else{ if(str.charAt(j-1) == d){ break; } } if(counter > 1){ d = str.charAt(i); } } if(counter > 1){ tmp += "[" + counter + str.charAt(i) + "]"; i+= counter - 1; }else{ tmp += str.charAt(i); } } System.out.println(tmp); } }
Output:
$ java CompressString Enter string: abbcccddddeeeeef a[2b][3c][4d][5e]f