Compare Two Strings without whitespaces Java Program - The Coding Shala

Home >> Java Programs >> Compare two strings by ignoring whitespaces

 In this post, we will learn how to compare two strings by ignoring white spaces and will implement the Java program for the same.

Compare Two Strings without WhiteSpaces Java Program

Problem
Write a program that reads two lines and compares them without whitespaces. The program should print true if both lines are equal, otherwise – false.

Example 1:
Input:      string
            str ing 
Output: true

Example 2: string
                    my string
Output: false

Approach
First, we will trim both the strings by removing leading and trailing spaces. If strings contain spaces in between then we will remove that also, then will compare both the strings and return accordingly.

Java Program:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        // put your code here
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        s1 = s1.trim().replace(" ", "");
        s2 = s2.trim().replace(" ", "");
        if (s1.equals(s2)) {
            System.out.println(true);
        } else {
            System.out.println(false);
        }
    }
}

Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala