为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

红糖糍粑 2022-06-04 15:54:38
我想在字符串数组中找到一个子字符串,而不使用循环。我在用着: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);        }    }}我总是找不到。这种方法有什么问题?
查看完整描述

3 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

您正在检查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.


查看完整回答
反对 回复 2022-06-04
?
慕的地6264312

TA贡献1817条经验 获得超6个赞

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


if (Arrays.stream(files).noneMatch(a -> a.endsWith(substring))) {

    System.out.println("Not found:" + substring);

}


查看完整回答
反对 回复 2022-06-04
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

我不是流专家,但我相信您想要这样的东西:


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

    }

}


查看完整回答
反对 回复 2022-06-04
  • 3 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号