I ran into a requirement working on a piece of code that needed me to search a string from beginning to end and then from end to the beginning. This is the solution that I came up with consists of three methods. One method to simulate the InStr function from the old vb days, one to reverse a string and another to do the actual matching:
public bool ForwardBackwardMatch(string stringSearched,
string searchCriteria)
{
bool matchFound = false;
if (stringSearched.Trim() != string.Empty)
{
// search criteria in string?
if (InStr(stringSearched, searchCriteria))
{
matchFound = true;
}
// reverse our string
string stringSearchedReverse =
StringReverse(stringSearched);
// recheck against criteria
if (InStr(stringSearchedReverse, searchCriteria))
{
matchFound = true;
}
}
return matchFound;
}
public bool InStr(string stringSearched, string searchCriteria)
{
bool returnVal;
if (stringSearched.IndexOf(searchCriteria.Trim()) == -1)
{
returnVal = false;
}
else
{
returnVal = true;
}
return returnVal;
}
public string StringReverse(string s)
{
char[] charArray = s.ToCharArray();
for (int i = 0, j = charArray.Length - 1;
i < j; i++, j--)
{
charArray[j] = s[i];
charArray[i] = s[j];
}
return new String(charArray);
}