Search code examples
javastringcontainsmultilinestring

How to check If a multiline String contains another multiline String in Java?


1.I tried to use the contains function BUT it did not work, it only works when b = "30-10-1960\n" or b = "Posephine Esmerelda Bloggs\n". How to check if a contains b? 2.Here is the code I wrote.

String a = "name Posephine Esmerelda Bloggs\n" + 
        "birthday 30-10-1960\n" + 
        "address 102 Smith St, Summer hill, NSW 2130\n" + 
        "";
String b = "Posephine Esmerelda Bloggs\n" + 
        "30-10-1960\n";
System.out.println("a.contains(b)");

Solution

  • I think the logic you want here is to assert that every line of the b string appears somewhere in the a string:

    String a = "name Posephine Esmerelda Bloggs\n" + 
        "birthday 30-10-1960\n" + 
        "address 102 Smith St, Summer hill, NSW 2130\n" + 
        "";
    String b = "Posephine Esmerelda Bloggs\n" + 
        "30-10-1960\n";
    String[] lines = b.split("\n");
    
    // now check each line
    boolean all = true;
    for (String line : lines) {
        if (!a.contains(line)) {
            all = false;
            break;
        }
    }
    
    if (all) {
        System.out.println("MATCH");
    }
    else {
        System.out.println("NO MATCH");
    }
    

    This prints:

    MATCH