简体   繁体   English

在数组列表中搜索子字符串

[英]Search array list for substring

Let say I have an array list with names and the names are stored like this... 假设我有一个包含名称的数组列表,并且名称存储如下:

    John(2), 
    Bob(anytext), 
    Rick

I'm trying to iterate over my array list and check for "(" basically and just take the rest of the string behind it and return that as a string, and null if nothing there. I've seen methods to do similar things but I can't seem to find something to just return the rest of the string if it finds the "(" 我试图遍历我的数组列表,基本上检查“(”,然后将它后面的其余字符串作为字符串返回,如果没有,则返回null。我见过做类似事情的方法,但是我似乎找不到能返回字符串其余部分的东西(如果找到了“(”

for(int i=0; i<list.size(); i++) {
  String s = list.get(i);
  int x = s.indexOf('(');
  if(x==-1) break;
  return s.substring(x+1);
}

Pass the strings you want to check to a method that does something like this: 将您要检查的字符串传递给执行以下操作的方法:

        if(str.contains("(")){
           return str.substring(str.indexOf("("));
        }else{
            return null;
        }

Java 8 version Java 8版本

List<String> list = Arrays.asList("John(2)", "Bob(anytext)", "Rick");
String result = list.stream()
        .filter(x -> x.contains("("))
        .findFirst()
        .map(x -> x.substring(x.indexOf("(")))
        .orElse(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM