Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Strings in java without considering spaces?

Tags:

java

string

I have one example.

public class Test {     public static void main(String[] args) {         String a="VIJAY KAKADE";         String b="VIJAY    KAKADE";         if(a.equalsIgnoreCase(b)){             System.out.println("yes");         }else{             System.out.println("no");         }     } } 

I need to check these strings without considering spaces. How do I achieve this? How do I ignore spaces in the strings when I compare them?

like image 632
vijayk Avatar asked Jul 31 '13 15:07

vijayk


People also ask

How do I ignore a space character in Java?

You can implicitly ignore them by just removing them from your input text. Therefore replace all occurrences with "" (empty text): fullName = fullName. replaceAll(" ", "");

How do I remove white spaces between strings in Java?

Java For Testers The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do you check if a string is just spaces Java?

isBlank() method to determine is a given string is blank or empty or contains only white spaces. isBlank() method has been added in Java 11. To check is given string does not have even blank spaces, use String.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


1 Answers

You can try to create a new string by replacing all empty spaces.

if(a.replaceAll("\\s+","").equalsIgnoreCase(b.replaceAll("\\s+",""))) {    // this will also take care of spaces like tabs etc. } 

then compare.

like image 75
AllTooSir Avatar answered Sep 18 '22 19:09

AllTooSir