vijayk vijayk - 3 months ago 12
Java Question

How compare two string without considering spaces and case of string in java?

I have this code:

public class TestString {

public static void main(String[] args) {
String a = "Vijay Kakade";
String b = "vij";

if (a.contains(b)) {
System.out.println("11");
} else {
System.out.println("22");
}
}
}


This example should return 11 but it returns 22.

Answer

Use replace() to remove spaces, and use toLowerCase() to bring both strings to the same case, then use contains():

if (a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))

To make this null safe (defining null as not equal to anything, not even another null):

if (a != null && b != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))

Or, if null is considered "equal" to another null:

if (!((a == null) ^ (b == null)) || a != null && a.replace(" ", "").toLowerCase().contains(b.replace(" ", "").toLowerCase()))
Comments