First index before a position

前端 未结 5 1910
天涯浪人
天涯浪人 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:22

    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");
    
    0 讨论(0)
  • 2021-01-21 19:22

    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");

    0 讨论(0)
  • 2021-01-21 19:27

    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.

    0 讨论(0)
  • 2021-01-21 19:30

    Try something like:

    var res = yourString.Substring(0, index).LastIndexOf(stringToMatch);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题