patterncsharpMinor
Algorithm to find substring in a string
Viewed 0 times
algorithmstringsubstringfind
Problem
Can this be improved?
static int find(string term, string text)
{
int found = -1;
int termIndex = 0;
for (int textIndex = 0; textIndex < text.Length; textIndex++)
{
if (term[termIndex] == text[textIndex])
{
if (termIndex == term.Length-1)
return found;
if (termIndex == 0)
found = textIndex;
termIndex++;
}else
{
termIndex = 0;
found = -1;
}
}
return found;
}Solution
I also don't code in C#, but if I'm right the following is the same in Java:
Unfortunately, it does not seem to work. Here are some test cases:
public static int find(final String term, final String text) {
int found = -1;
int termIndex = 0;
for (int textIndex = 0; textIndex < text.length(); textIndex++) {
if (term.charAt(termIndex) == text.charAt(textIndex)) {
if (termIndex == term.length() - 1) {
return found;
}
if (termIndex == 0) {
found = textIndex;
}
termIndex++;
} else {
termIndex = 0;
found = -1;
}
}
return found;
}Unfortunately, it does not seem to work. Here are some test cases:
assertEquals("#0", 3, find("de", "abcde")); // OK
assertEquals("#1", 1, find("a", "ababaa")); // fails, returns -1
assertEquals("#2", 1, find("ba", "ababaa")); // OK
assertEquals("#3", 2, find("abaa", "ababaa")); // fails, returns -1
assertEquals("#4", 2, find("abaa", "ababaacc")); // fails, returns -1Code Snippets
public static int find(final String term, final String text) {
int found = -1;
int termIndex = 0;
for (int textIndex = 0; textIndex < text.length(); textIndex++) {
if (term.charAt(termIndex) == text.charAt(textIndex)) {
if (termIndex == term.length() - 1) {
return found;
}
if (termIndex == 0) {
found = textIndex;
}
termIndex++;
} else {
termIndex = 0;
found = -1;
}
}
return found;
}assertEquals("#0", 3, find("de", "abcde")); // OK
assertEquals("#1", 1, find("a", "ababaa")); // fails, returns -1
assertEquals("#2", 1, find("ba", "ababaa")); // OK
assertEquals("#3", 2, find("abaa", "ababaa")); // fails, returns -1
assertEquals("#4", 2, find("abaa", "ababaacc")); // fails, returns -1Context
StackExchange Code Review Q#13606, answer score: 5
Revisions (0)
No revisions yet.