简体   繁体   English

如何检查文本段落是否包含字符串数组中可用的单词?

[英]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变量和String数组中的文本段落,其中包含多个值,例如

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? 如何检查文本段落(存储在String变量中)是否包含名称数组中给定的值?

Lonely Neuron method checks and returns true if any one of the string in array is present in the paragraph. 如果段落中存在数组中的任何字符串,Lonely Neuron方法将检查并返回true。

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 . Jackjack

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. 随着for (String name : names) ,我们遍历所有值names ,所以我们可以检查每name独立。 We then call text.contains(name) to check if that particular name is contained. 然后,我们调用text.contains(name)来检查是否包含该特定名称。 If any name is contained, it immediately returns true and the rest of the loop doesn't have to get executed. 如果包含任何名称,它将立即返回true并且循环的其余部分不必执行。 If we have tested all name s, it will return false , indicating no names was contained in the text . 如果我们测试了所有name s,它将返回false ,表示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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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