First index before a position

前端 未结 5 1916
天涯浪人
天涯浪人 2021-01-21 18:49

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

5条回答
  •  不思量自难忘°
    2021-01-21 19:42

    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.

提交回复
热议问题