Search code examples
c#arrayssubstringcontainslastindexof

Check if string contains string from an array then use that in LastIndexOf method


I want to check if my input string contains one of 3 strings and use it later on. Here's what I have so far:

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

I want to check which string from the array has the Contains method found and use exactly that one in the LastIndexOf method. Am I on the right track here?

EDIT:

Sorry for any confusion here. titleID.LastIndexOf(string) <- the string is just a dummy and it represents what I'd like to achieve here. I was previously using the Contains method to check only for 1 of the values f.eg. if(titleID.Contains"ended ") and then I'd do titleID.LastIndexOf("ended "). I could have 3 separate blocks each based on "ended", "Ended" or "Ending" using each one in the LastIndexOf method but I want to make it more simple and flexible towards the input, otherwise I'd have 3 times more code and I would like to avoid that.

EDIT NR 2:

How would I achieve the same result if I couldn't use System.Linq? Cause the solution provided here works when I test it in the IDE, but the software itself which will be using this code doesn't give me the possibility declare "using System.Linq". I'm thinking I need to have something like System.Linq.Enumerable.FirstOrDefault.


Solution

  •         // 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));
            }