如何在容错为1个或更多字符的字符串中查找子字符串的出现次数?
实施例。
来源:John Smith
容错1个字符:
容错2字符:
任何正则表达式解决方案? Java模式匹配?在这种情况下,像这样的方法
int countOccurrenceWithFaultTolerance(String source, String subString, int faultTolerance) {
// TODO
return 0;
}
答案 0 :(得分:0)
可能是我发现了这个,
public class HelloWorld{
public static void main(String []args){
final int mismatchTolerance = 1;
final String text = "bubbles";
final String pattern = "bu";
final int textIndexMax = text.length() - pattern.length() + 1;
for (int textIndex = 0; textIndex < textIndexMax; textIndex++) {
int missed = 0;
for (int patternIndex = 0; patternIndex < pattern.length(); patternIndex++) {
final char textChar = text.charAt(textIndex + patternIndex);
final char patternChar = pattern.charAt(patternIndex);
if (textChar != patternChar) {
missed++;
}
if (missed > mismatchTolerance) {
break;
}
}
if (missed <= mismatchTolerance) {
final String match = text.substring(textIndex, textIndex + pattern.length());
System.out.println("Index: " + textIndex + " Match: " + match);
}
}
}
}