vijayk vijayk - 1 year ago 97
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)) {
} else {

This example should return 11 but it returns 22.

Answer Source

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()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download