Java,如果列表中的修剪字符串包含字符串,则返回 [英] Java, return if trimmed String in List contains String

查看:35
本文介绍了Java,如果列表中的修剪字符串包含字符串,则返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我想检查List中是否存在StringmyList.

In Java, I want to check whether a String exists in a List<String> myList.

像这样:

if(myList.contains("A")){
    //true
}else{
    // false
}

问题是 myList 可以包含未修剪的数据:

The problem is myList can contain un-trimmed data:

{'  A', 'B  ', '  C  '}

如果我的项目 'B' 在列表中,我希望它返回 true.我该怎么做?我想避免循环结构.

I want it to return true if my item 'B' is in the list. How should I do this? I would like to avoid a looping structure.

推荐答案

您需要迭代您的列表并调用 String#trim 用于搜索:

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

或者如果您想执行忽略大小写搜索,请使用:

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

这篇关于Java,如果列表中的修剪字符串包含字符串,则返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆