C# 位置前的第一个索引

C# 位置前的第一个索引,c#,string,C#,String,我有一个字符串和该字符串中的索引,并希望得到该索引之前的子字符串的第一个位置 e、 例如,字符串: “这是一个包含其他测试字符串的测试字符串” 是否有以下功能: 给定子字符串“string”和起始位置53,返回42;及 返回15,给定子字符串“string”和起始位置30 尝试以下方法: var res = yourString.Substring(0, index).LastIndexOf(stringToMatch); 所以你想要在给定索引之前的最后一个索引 var myString =

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

e、 例如,字符串:

“这是一个包含其他测试字符串的测试字符串”

是否有以下功能:

  • 给定子字符串
    “string”
    和起始位置53,返回42;及
  • 返回15,给定子字符串
    “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");
与IndexOf()一样,lastIndexOf也为您提供了一个从倒退开始的位置

var myString = "this is a test string that contains other string for testing";
var lastIndexOf = myString.LastIndexOf("string", 30);
报告此实例中指定字符串最后一次出现的从零开始的索引位置。搜索从指定的字符位置开始,向后搜索字符串的开头


您只需将子字符串从0带到索引,然后在此子字符串上请求它的最后一个索引


YourString.substring(0,index.LastIndexOf(“字符串”)

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

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

我在您的示例中进行了测试,得到了预期的结果。

这显然是最好的答案。不需要中间字符串,只需使用内置功能。这可能会消耗大量CPU。另一个答案要好得多