In my current project I had requirement to find if given string starts with any of provided prefixes or not. If yes then do special handling otherwise normal processing.
There are few ways to achieve this, mentioned below. Please comment if you know any better way or problem in below approaches.
(1) Iteration and use startsWith() method
This has limitation if search string varies over period of time, we might need to recompile code.
This will take longer if search string list is too large
static void javaStdWay(String testString, List<String> searchStringList) {
boolean flag = false;
for (String searchSt : searchStringList) {
if (testString.toUpperCase().startsWith(searchSt.toUpperCase())) {
System.out.println("TestString {" + testString + "} starts with " + searchSt);
flag = true;
}
}
if (!flag) {
System.out.println("TestString {" + testString + "} does not start with any search string" + searchStringList);
}
}
(2) Regex way : This looks better as we can add regex in property file and application restart will take care of new regex.
static void regexWay(String testString, List<String> searchList) {
String pattern = "";
boolean flag = false;
for (String searchSt : searchList) {
if (!pattern.isEmpty()) {
pattern = pattern + "|" + searchSt;
} else {
pattern = searchSt;
}
}
if (testString.matches("(" + pattern + ").*")) {
System.out.println("TestString {" + testString + "} starts with one of the " + searchList);
flag = true;
}
if (!flag) {
System.out.println("TestString {" + testString + "} does not start with any search string" + searchList);
}
}
(3) Apache commons lang lib use. This looks more promising as it handles null and other cases efficiently.
static void apacheWay(String testString, List<String> searchStringList) {
boolean flag = false;
if (StringUtils.startsWithAny(testString, searchStringList.toArray(new String[searchStringList.size()]))) {
System.out.println("TestString {" + testString + "} starts with one of the " + searchStringList);
flag = true;
}
if (!flag) {
System.out.println("TestString {" + testString + "} does not start with any search string" + searchStringList);
}
}
Main method of program for execution of above three methods.
public static void main(String[] args) {
String testString = "US.Newyork"; // DE.Essen
List<String> searchStringList = new ArrayList<String>();
searchStringList.add("US");
searchStringList.add("UK");
searchStringList.add("NZ");
searchStringList.add("IN");
regexWay(testString, searchStringList);
javaStdWay(testString, searchStringList);
apacheWay(testString, searchStringList);
}
Output:
TestString {US.Newyork} starts with one of the [US, UK, NZ, IN]
TestString {US.Newyork} starts with US
TestString {US.Newyork} starts with one of the [US, UK, NZ, IN]
Comments and suggestions are welcome.