简体   繁体   中英

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.

You can replace spaces and use equalsIgnoreCase :

if (a.replace(" ", "").equalsIgnoreCase(b.replace(" ", ""))) {

If you want to also disregard other whitespace characters you can use replaceAll :

if (a.replaceAll("\\s", "").equalsIgnoreCase(b.replaceAll("\\s", ""))) {

If you want instead to check for containment , use contains and toLowerCase :

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

Again, if you want to disregard other whitespace character use replaceAll("\\\\s", "") as shown above.

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()))

Try this

     String a = "V    i     jay Kakade";
        String b = "vI  j";
        if (a.toLowerCase().replaceAll("\\s", "").trim().contains(b.trim().toLowerCase().replaceAll("\\s", ""))) {
            System.out.println("11");
        } else {
            System.out.println("22");
        }

Set both a and b to lowercase and remove spaces, then make your comparison:

    String a = " V I J a y Kakade";
    String b = " V i j ";

    a = a.toLowerCase().replaceAll("\\s","");
    b = b.toLowerCase().replaceAll("\\s","");

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

String a = " VIJ ay Kakade"; String b = " V ij ";

a = a.toLowerCase().replaceAll("\\s","");
b = b.toLowerCase().replaceAll("\\s","");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM