简体   繁体   中英

How to check if a text paragraph contains words available in string array?

I have a text paragraph stored in String variable and String array containing multiple values like

String names[] = {"jack", "adam", "jerry adams", "Jon snow"};

How do i check if text paragraph ( which is stored in String variable) contains the value given in name array?

Lonely Neuron method checks and returns true if any one of the string in array is present in the paragraph.

To check if all values in array(as mentioned in comment) are present in paragraph, this slight modification would be needed.

public static boolean textContainsAny(String text, String[] names) {
    for (String name : names) {
        if (!text.contains(name)) {
            return false;
        }
    }
    return true;
}

This may be slightly advanced, but:

String names[] = {"jack", "adam", "jerry adams", "Jon snow"};
String paragraph = "jack and jill went up the hill to meet jerry adams";
boolean onefound = Stream.of(names).anyMatch(paragraph::contains);
bollean allfound = Stream.of(names).allMatch(paragraph::contains);

You can use the following one-liner

boolean contained = Arrays.stream(names) .noneMatch(name -> !paragraph.contains(name));

Note that it is going to be a case sensitive match. Jack is not the same as jack .

This should do the trick:

public boolean textContainsAny(String text, String[] names) {
    for (String name : names) {
        if (text.contains(name)) {
            return true;
        }
    }
    return false;
}

With for (String name : names) we iterate over all values in names so we can check each name separately. We then call text.contains(name) to check if that particular name is contained. If any name is contained, it immediately returns true and the rest of the loop doesn't have to get executed. If we have tested all name s, it will return false , indicating no names was contained in the text . We do this in a separate method so the code is reusable.

You can then call it like that:

public static void main(String[] args) {
    String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore";
    String names = new String[]{"jack", "adam", "jerry adams", "Jon snow"};
    System.out.println("name is contained: " + textContainsAny(text, names));
}

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