Hanging Letter Program

Avishek Datta Ray :

I was practicing problems in JAVA for the last few days and I got a problem like this:

I/p: I Am A Good Boy

O/p:

I A A G B
  m   o o
      o y
      d

This is my code.

System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
    char c = s.charAt(i);
    if(c!=32)
    {s1+=c;}
    else
    {
        for(int j=0;j<s1.length();j++)
        {System.out.println(s1.charAt(j));}
        s1="";
    }
}

The problem is I am not able to make this design.My output is coming as each character in each line.

YouKnowWhoIAm :

First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()

After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.

You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.

Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,

import java.io.*;
import java.util.*;
public class MyClass {
    public static void main(String args[]) throws IOException{
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Scanner sc = new Scanner(System.in);
        String[] s = sc.nextLine().split(" ");
        // Split is a String function that uses regular function to split a string, 
        // apparently you can strings like a space given above, the regular expression 
        // for space is \\s or \\s+ for multiple spaces
        int max = 0;
        for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
        int count = 0;
        while(count<max){ // iterate till the longest string exhausts
            for(int i=0;i<s.length;i++){
                if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
                else System.out.print("  "); // Two spaces otherwise
            }
            System.out.println();count++;
        }
    }
}

Edit: I am sharing the output below for the string This is a test Input

T i a t I 
h s   e n 
i     s p 
s     t u 
        t   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=148282&siteId=1