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

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

问题描述

在Java中,我要检查List<String> myList中是否存在字符串.

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.

推荐答案

您需要迭代列表并调用

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天全站免登陆