位置前的第一个索引

本文关键字:索引 第一个 位置 | 更新日期: 2023-09-27 18:00:45

我在该字符串中有一个字符串和索引,并且希望在该索引之前获得子字符串的第一个位置。

例如,字符串中:

"this is a test string that contains other string for testing"

有没有一个功能:

  • 返回42,给定子字符串"string"和起始位置53;以及
  • 返回15,给定子字符串"string"和起始位置30

位置前的第一个索引

与IndexOf()一样,lastIndexOf也为您提供了一个从向后开始的位置

var myString = "this is a test string that contains other string for testing";
var lastIndexOf = myString.LastIndexOf("string", 30);

报告此实例中指定字符串最后一次出现的从零开始的索引位置。搜索从指定的字符位置开始,并向后朝字符串的开头进行。

尝试以下操作:

var res = yourString.Substring(0, index).LastIndexOf(stringToMatch);

因此,您需要给定索引之前的最后一个索引。。。

var myString = "this is a test string that contains other string for testing";
myString = String.SubString(0, 53);
var lastIndexOf = myString.LastIndexOf("string");

您可以简单地将子字符串从0带到索引,并在此子字符串上请求它的最后一个索引

YourString.substring(0,index).LastIndexOf("string");

我知道我迟到了,但这是我正在使用的解决方案:

    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;
    }

我在你的例子中测试了它,它给出了预期的结果。