Tanvir Sourov
Tanvir Sourov

Reputation: 417

Get Shortest String between two Words C#

I want to get the shortest string between two given words. I can get the string between two words, but the problem happens if there is same word twice.

Sentence: The people who were working with other people are here.

I want to get the string between the last people and here. This is the method I am currently using:

private static string Between(this string value, string a, string b)
{
    int posA = value.IndexOf(a);
    int posB = value.LastIndexOf(b);
    if (posA == -1)
    {
        return "";
    }
    if (posB == -1)
    {
        return "";
    }
    int adjustedPosA = posA + a.Length;
    if (adjustedPosA >= posB)
    {
        return "";
    }
    return value.Substring(adjustedPosA, posB - adjustedPosA);
}

This function works if there is no repeat. But for the example it returns me all the string between the first people and here. How can I get the result between the last people and here? The result I am expecting is are.

Upvotes: 0

Views: 308

Answers (1)

NineBerry
NineBerry

Reputation: 28499

Use LastIndexOf When looking for both words, so that you always find the last occurence of the word.

   int posA = value.LastIndexOf(a);
   int posB = value.LastIndexOf(b);

However: this might not produce what you want for "The people who were working here with other people". Please clarify your requirements

Other Solution using regular expressions at https://stackoverflow.com/a/35105389/101087

Upvotes: 2

Related Questions