检查字符串是否包含数组中的字符串,然后在LastIndexOf方法中使用它

时间:2014-06-26 07:31:08

标签: c# arrays substring contains lastindexof

我想检查输入字符串是否包含3个字符串中的一个,稍后再使用它。这是我到目前为止所做的:

// this is just an example of 1 out of 3 possible variations
string titleID = "document for the period ended 31 March 2014";

// the array values represent 3 possible variations that I might encounter
string s1 = "ended ";
string s2 = "Ended ";
string s3 = "Ending ";
string[] sArray = new [] { s1, s2, s3};

if(sArray.Any(titleID.Contains))
{
      TakeEndPeriod = titleID.Substring(titleID.LastIndexOf(string));
}

我想检查数组中的哪个字符串找到了Contains方法,并在LastIndexOf方法中使用该字符串。我在这里走在正确的轨道上吗?

编辑:

很抱歉这里有任何混淆。 titleID.LastIndexOf(string)< - 字符串只是一个虚拟,它代表了我想在这里实现的目标。我以前使用Contains方法只检查f.eg中的1个值。如果(titleID.Contains“结束”)然后我会做titleID.LastIndexOf(“已结束”)。我可以在LastIndexOf方法中使用每个基于“结束”,“结束”或“结束”的3个单独的块,但是我想使它对输入更简单和灵活,否则我将有3倍的代码我想避免这种情况。

编辑NR 2:

如果我无法使用System.Linq,我将如何获得相同的结果?因为这里提供的解决方案在我在IDE中测试时有效,但是使用此代码的软件本身并没有给我声明“使用System.Linq”的可能性。我想我需要像System.Linq.Enumerable.FirstOrDefault这样的东西。

2 个答案:

答案 0 :(得分:3)

        // this is just an example of 1 out of 3 possible variations
        string titleID = "document for the period ended 31 March 2014";

        // the array values represent 3 possible variations that I might encounter
        string s1 = "ended ";
        string s2 = "Ended ";
        string s3 = "Ending ";
        string[] sArray = new [] { s1, s2, s3};

        var stringMatch = sArray.FirstOrDefault(titleID.Contains);
        if (stringMatch != null)
        {
            TakeEndPeriod = titleID.Substring(titleID.LastIndexOf(stringMatch));
        }

答案 1 :(得分:0)

这应该这样做。

// this is just an example of 1 out of 3 possible variations
string titleID = "document for the period ended 31 March 2014";

string s1 = "ended ";
string s2 = "Ended ";
string s3 = "Ending ";
string[] sArray = new [] { s1, s2, s3};

var maxLastIndex = -2; 
foreach(var s in sArray)
{
    var lastIndex = titleID.LastIndexOf(s);
    if(lastIndex > maxLastIndex)
        maxLastIndex = lastIndex;
}

/// if maxLastIndex is still -1 it means no matching elements exist in the string.
相关问题