Which is the best way to check if a Java String A contains another String B, even if B chars are not contiguous?
For example: "takaderoka" contains "tkdr" but not "tkkr".
Is there a built-in function, or do I have to write my own? Thank you.
Which is the best way to check if a Java String A contains another String B, even if B chars are not contiguous?
For example: "takaderoka" contains "tkdr" but not "tkkr".
Is there a built-in function, or do I have to write my own? Thank you.
No built-in function, but can be done on one line:
"takaderoka".matches("tkkr".replace("", ".*"));
Or put it in a function:
static boolean matcher(String one, String two) {
return one.matches(two.replace("", ".*"));
}
A simple java program that you can use as utility method. [order is also considered.]
public static boolean isMatched(String s1, String s2) {
int index = -1;
for (char ch : s2.toCharArray()) {
if ((index = s1.indexOf(ch, index + 1)) == -1) {
return false;
}
}
return true;
}
...
System.out.println(isMatched("takaderoka", "tkdr")); // true
System.out.println(isMatched("takaderoka", "tkkr")); // false
you can make it more optimized:
public static boolean isMatched(String s1, String s2) {
if ((s1.length() > 0 && s2.length() == 0) || (s2.length() > s1.length())) {
return false;
} else if (s1.indexOf(s2) != -1 || s1.equals(s2)) {
return true;
} else {
int index = -1;
for (char ch : s2.toCharArray()) {
if ((index = s1.indexOf(ch, index + 1)) == -1) {
return false;
}
}
}
return true;
}
You could do a regular expression matching on your search string with ".*" inserted between each character, alternatively just write your own searching for each character in turn.
There is contains() method for the String class which you can use. Check out the method for the String class and also Regex expressions in Java.
I'd use apache commons StringUtils.getLevenshteinDistance() function.
Basically, it measures how many modifications you have to make to transform one string into another. So your problem is quite the same as knowing if transforming all the other letters into nulls is the same as the difference between their lengths.
for example
StringUtils.getLevenshteinDistance("takaderoka","tkdr"); //6,
StringUtils.getLevenshteinDistance("takaderoka","tkkr"); //7,
if the result = "takaderoka".length - "tkdr".length = 6, then "takaderoka" contains "tkdr"
You could this method. Could be refactored to have better code.
private boolean contains(String source, String toMatch) {
boolean result = false;
if (toMatch.length() == 0 || source.length() == 0) {
return result;
}
int j = 0;
for (int i = 0; i < source.length(); i++) {
if (toMatch.length() - j > source.length() - i) {
break;
}
if (source.charAt(i) == toMatch.charAt(j)) {
j++;
}
if (j == toMatch.length()) {
result = true;
break;
}
}
return result;
}