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

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

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(;
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        s1 = s1.trim().replace(" ", "");
        s2 = s2.trim().replace(" ", "");
        if (s1.equals(s2)) {
        } else {

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.


Popular Posts from this Blog

Anti Diagonals - The Coding Shala

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

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala