Compare Two Strings without whitespaces Java Program - The Coding Shala
Home >> Java Programs >> Compare two strings by ignoring whitespaces
Other Posts You May Like
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
- Java Program to check leap year
- Java Program to Reverse a String
- Java Program to find Duplicate characters count
- Java Program to Add Two Numbers
- Java Program to find the sum of digits of a number
Comments
Post a Comment