Close

Java - How to test if a string starts or ends with any of the provided substrings?

[Updated: May 19, 2018, Created: May 19, 2018]

Java String Manipulation Java 

Following code shows how to test if a string starts or ends with any of the given substrings. The method containsAny() is a general purpose method for String operations, based on Stream#anyMatch().

package com.logicbig.example;

import java.util.Arrays;
import java.util.Objects;
import java.util.function.BiPredicate;

public class StartsOrEndsWithAny {

  public static boolean startsWithAny(String input, boolean ignoreCase, String... prefixes) {
      return matchAny(input, ignoreCase, prefixes, String::startsWith);
  }

  public static boolean endsWithAny(String input, boolean ignoreCase, String... suffixes) {
      return matchAny(input, ignoreCase, suffixes, String::endsWith);
  }

  public static boolean containsAny(String input, boolean ignoreCase, String... substrings){
       return matchAny(input, ignoreCase, substrings, String::contains);
  }

  public static boolean matchAny(String input, boolean ignoreCase, String[] toMatchAny,
                                 BiPredicate<String, String> biPredicate) {
      if (input == null || toMatchAny == null || toMatchAny.length == 0) {
          return false;
      }
      if (ignoreCase) {
          input = input.toLowerCase();
      }
      String finalInput = input;
      return Arrays.stream(toMatchAny)
                   .filter(Objects::nonNull)
                   .filter(s -> s.length() > 0)
                   .map(s -> ignoreCase ? s.toLowerCase() : s)
                   .anyMatch(s -> biPredicate.test(finalInput, s));
  }

  public static void main(String[] args) {
      String input = "Taffy Piccolo Seamus Willie";
      boolean b = startsWithAny(input, true, "taffy", "bramble");
      System.out.println(b);
      b = endsWithAny(input, true, "toby", "willie");
      System.out.println(b);
      b = startsWithAny(input, true, "coco");
      System.out.println(b);
      b = endsWithAny(input, true, null, "");
      System.out.println(b);
      b = containsAny(input, true, "seamus", "bonnie");
      System.out.println(b);
  }
}
true
true
false
false
true

See Also