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

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


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);

        }

    }

}

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


红糖糍粑
浏览 129回答 3
3回答

慕神8447489

您正在检查String“.csv”是否不包含您的任何元素Stream,这与您想要的相反。它应该是:if (!Arrays.stream(files).anyMatch(s -> s.contains(substring))) {    System.out.println("Not found:" + substring);}PS 正如评论的那样,您可以使用noneMatch而不是anyMatch,这将节省否定条件的需要:if (Arrays.stream(files).noneMatch(s -> s.contains(substring))) {    System.out.println("Not found:" + substring);}并且如果“.csv”子字符串只应在String(即视为后缀)的末尾搜索,则应使用endsWith而不是contains.

慕的地6264312

您可能需要检查文件扩展名并可以使用endsWith它来改善您的状况:if (Arrays.stream(files).noneMatch(a -> a.endsWith(substring))) {    System.out.println("Not found:" + substring);}

蝴蝶不菲

我不是流专家,但我相信您想要这样的东西: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");    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java