Java语句:String.contains(Stringarray)

问题描述 投票:0回答:2

我有一个字符串(line),我想检查此字符串是否包含某个句子。此句子保存在数组(StringArray)中。

public class example {

    String line = "I`ve got a Pc";

    public void test() throws Exception {
        String[] StringArray = new String[1];
        StringArray[0] = "Example sentence";
        StringArray[1] = "Pc";

       //I know this doesn´t work, but thats my problem
       if (line.contains(StringArray) {
            // doesn't matter what here should be
       }
java arrays string if-statement contains
2个回答
1
投票

我将流传输数组,然后检查字符串是否包含其任何元素:

if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
    // Do something...

0
投票

我更喜欢在这里使用正则表达式,并交替使用:

String line = "I`ve got a Pc";
String[] array = new String[2];
array[0] = "Example sentence";
array[1] = "Pc";
List<String> terms = Arrays.asList(array);
String regex = ".*\\b(?:" + String.join("|", terms) + ")\\b.*";
if (line.matches(regex)) {
    System.out.println("MATCH");
}
© www.soinside.com 2019 - 2024. All rights reserved.