1

我想检查我的输入字符串是否包含 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 方法仅检查 1 个值 f.eg。if(titleID.Contains"ended ") 然后我会做 titleID.LastIndexOf("ended ")。我可以在 LastIndexOf 方法中使用每个基于“结束”、“结束”或“结束”的 3 个单独的块,但我想让它对输入更加简单和灵活,否则我会有 3 倍的代码我想避免这种情况。

编辑 NR 2:

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

4

2 回答 2

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));
        }
于 2014-06-26T07:34:46.123 回答
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.
于 2014-06-26T07:46:51.757 回答