I have a string and index in that string, and want to get the first position of a substring before that index.
e.g., in string:
\"this is a test string tha
So you want the last index before a given index...
var myString = "this is a test string that contains other string for testing";
myString = String.SubString(0, 53);
var lastIndexOf = myString.LastIndexOf("string");
You can simply take the substring from 0 to index and on this substring ask for the last index of it
YourString.substring(0,index).LastIndexOf("string");
Like IndexOf() where you can start, lastIndexOf also gives you a place to start from going backwards
var myString = "this is a test string that contains other string for testing";
var lastIndexOf = myString.LastIndexOf("string", 30);
Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string.
Try something like:
var res = yourString.Substring(0, index).LastIndexOf(stringToMatch);
I know I am late to the party but this is the solution that I am using:
public static int FindIndexBefore(this string text, int startIndex, string searchString)
{
for (int index = startIndex; index >= 0; index--)
{
if (text.Substring(index, searchString.Length) == searchString)
{
return index;
}
}
return -1;
}
I tested it on your example and it gave the expected results.