检查字符串数组是否包含没有循环的子字符串

oyxsuwqo  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(415)

我想在字符串数组中找到一个子字符串,而不使用循环。我正在使用:

import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {

        String[] files = new String[]{"Audit_20190204_061439.csv","anotherFile"};
        String substring= ".csv";

        if(!Arrays.stream(files).anyMatch(substring::contains)) {
            System.out.println("Not found:" + substring);
        }
    }
}

我总是找不到。这种方法有什么问题?

tzdcorbm

tzdcorbm1#

您正在检查 String “.csv”不包含 Stream ,这和你想要的正好相反。
应该是:

if (!Arrays.stream(files).anyMatch(s -> s.contains(substring))) {
    System.out.println("Not found:" + substring);
}

p、 如前所述,您可以使用 noneMatch 而不是 anyMatch ,这将省去否定条件的需要:

if (Arrays.stream(files).noneMatch(s -> s.contains(substring))) {
    System.out.println("Not found:" + substring);
}

如果“.csv”子字符串只应在 String (即作为后缀处理),您应该使用 endsWith 而不是 contains .

h22fl7wq

h22fl7wq2#

您可能需要检查文件扩展名,并可以使用 endsWith 并改善您的状况:

if (Arrays.stream(files).noneMatch(a -> a.endsWith(substring))) {
    System.out.println("Not found:" + substring);
}
jmp7cifd

jmp7cifd3#

我不是古鲁,但我相信你想要这样的东西:

String[] files = new String[] { "Audit_20190204_061439.csv", "anotherFile" };

for (String file : files) {
    if (file.endsWith(".csv")) {
        System.out.println("found a CSV file");
    }
}

我用 String#endsWith 在这里,大概是因为 .csv 引用文件扩展名,只有在文件名末尾出现时才应注册命中。
我们也可以用 String#matches 在这里:

Pattern pattern = Pattern.compile(".*\\.csv$");
for (String file : files) {
    Matcher matcher = pattern.matcher(file);
    if (matcher.find()) {
        System.out.println("found a CSV file");
    }
}

相关问题