w3resource

Java Exercises: Restore the original string by entering the compressed string with this rule

Java Basic: Exercise-238 with Solution

When character are consecutive in a string , it is possible to shorten the character string by replacing the character with a certain rule. For example, in the case of the character string YYYYY, if it is expressed as # 5 Y, it is compressed by one character.
Write a Java program to restore the original string by entering the compressed string with this rule. However, the # character does not appear in the restored character string.
Note: The original sentences are uppercase letters, lowercase letters, numbers, symbols, less than 100 letters, and consecutive letters are not more than 9 letters.

Input:
Multiple character strings are given. One string is given per line.
Output: The restored character string for each character on one line.

Sample Solution:

Java Code:

import java.util.*;
public class Main 
{
    public static void main(String[] args) 
    {
        Scanner stdIn = new Scanner(System.in);
		    System.out.println("Input the text:");
            String str = stdIn.next();
            for(int i = 0; i < str.length(); ++i)
            {
                if(str.charAt(i) == '#')
                {
                    for(int j = 0; j < (str.charAt(i + 1) - '0'); ++j)
                    {
                        System.out.print(str.charAt(i + 2));
                    }
                    i += 2;
                }
                else
                {
                    System.out.print(str.charAt(i));
                }
            }
            System.out.println();
    }
}

Sample Output:

Input the text:
XY#6Z1#4023
XYZZZZZZ1000023

Pictorial Presentation:

Java exercises: Restore the original string by entering the compressed string with this rule.
Java exercises: Restore the original string by entering the compressed string with this rule.

Flowchart:

Flowchart: Restore the original string by entering the compressed string with this rule.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to read the mass data and find the number of islands.
Next: Write a Java program to cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters.

What is the difficulty level of this exercise?



Java: Tips of the Day

Directory Content:

Java allows you to get the names of all subdirectories and files in a folder as an array, which can then be sequentially viewed.

import java.io.*;
  
public class ListContents {
  public static void main(String[] args) {
    File file = new File("//home//user//Documents/");
    String[] files = file.list();
  
    System.out.println("Listing contents of " + file.getPath());
    for(int i=0 ; i < files.length ; i++)
    {
      System.out.println(files[i]);
    }
  }
}