I read article with nice exercise about checking is string is a substring of another.
The content of the exercise is:
Write a program that takes 2 string parameters from the command line. Program must verify if the second string is a substring of the first string (you cannot use substr, substring or any other standard function including regular expression libraries).
Each occurrence of * in the second substring means that it can be a match for zero or more characters of the first string.
Consider the example: Input string 1: abcd Input string 2: a*c Program should evaluate that the string 2 is a substring of the string 1.
Additionally asterisk (*) may be considered as a regular character, if it is preceded by a backslash (\). Backslash (\) is considered as a regular character in all cases other than preceding the asterisk (*).
I wrote simple app, which firstly check that second string is NOT longer than first(but there is one problem, when test at ("ab", "a*b") this is correct test, but the method fails):
public static boolean checkCharactersCount(String firstString, String secondString) {
return (firstString.length() > 0 && secondString.length() > 0) &&
(firstString.length() > secondString.length());
... and next verify is a subtring:
public static boolean checkSubstring(String firstString, String secondString) {
int correctCharCounter = 0;
int lastCorrectCharAtIndex = -1;
for (int i = 0; i < secondString.length(); i++) {
for (int j = 0; j < firstString.length(); j++) {
if (j > lastCorrectCharAtIndex) {
if ((secondString.charAt(i) == firstString.charAt(j)) || secondString.charAt(i) == '*') {
correctCharCounter++;
lastCorrectCharAtIndex = j;
}
if (correctCharCounter >= secondString.length())
return true;
}
}
}
return false;
}
But there are two problems:
- My code as above does not support character continuity(for example test: checkSubstring("abacd", "bcd") return true, but it is wrong! - should return false)
- Any idea how to verify special symbol as "\*" ? Sample to test (checkSubstring("abc", "\b")
How is Your vision of solution? :)
\\*is a backslash (the first one) followed by a literal asterisk.