phrail
phrail

Reputation: 7

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 "("

Upvotes: 0

Views: 606

Answers (3)

Dmitry Gorkovets
Dmitry Gorkovets

Reputation: 2286

Java 8 version

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

Upvotes: 0

user6683825
user6683825

Reputation:

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

Upvotes: 1

Alex
Alex

Reputation: 827

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

Upvotes: 0

Related Questions