Instagram
youtube
Facebook
Twitter

String operations program with Java HackerRank Solutions

Problem

Given two strings of lowercase English letters, A and B, perform the following operations:

Sum the lengths of A and B..
Determine if A is lexicographically larger than B (i.e.: does B come before A in the dictionary?).
Capitalize the first letter in A and B and print them on a single line, separated by a space.

Input Format

The first line contains a string A. The second line contains another string B. The strings are comprised of only lowercase English letters.

Output Format

There are three lines of output:
For the first line, sum the lengths of A and B.
For the second line, write Yes if A is lexicographically greater than B otherwise print No instead.
For the third line, capitalize the first letter in both A and B and print them on a single line, separated by a space.

Sample Input

hello
java

Sample Output

9
No
Hello Java

Explanation

String A is "hello" and B is "java".

A has a length of 5, and B has a length of 4; the sum of their lengths is 9.
When sorted alphabetically/lexicographically, "hello" precedes "java"; therefore, A is not greater than B and the answer is No.

When you capitalize the first letter of both A and B and then print them separated by a space, you get "Hello Java".

Solution

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        String B=sc.next();
        /* Enter your code here. Print output to STDOUT. */
        int sum=A.length()+B.length();
        System.out.println(sum);
        int n=A.compareTo(B);
        if(n>0)
        {
            System.out.println("Yes");
        }
        else
        {
            System.out.println("No");
        }
        String output = A.substring(0, 1).toUpperCase() + A.substring(1);
        String output2 = B.substring(0, 1).toUpperCase() + B.substring(1);
        System.out.println(output+" "+output2);
    }
}

Steps involved in this solution:

1. Import java.io.* and java.util.* packages.

2. Declare the class 'Solution' where the main method and program logic reside.

3. An instance of the Scanner class, 'sc', is created to read input strings from the user.

4. The lengths of strings A and B are added together to calculate the sum.The sum is printed to the standard output.

5. The compareTo method is used to lexicographically compare strings A and B.If A is lexicographically greater than B, "Yes" is printed. Otherwise, "No" is printed.

6. The first letter of each string, A and B, is capitalized using substring and toUpperCase methods.The modified strings are then printed to the standard output, separated by a space.