MDaruwalla MDaruwalla - 1 month ago 16
C# Question

How to find the words on the left and right of the searched word

How can I find left and right word in string from selected word string may contain, for example I have a string:

string input = "all our vidphone lines here are trapped. they recirculate the call to other offices within the building";

var word = new List<string> { "other", "they", "all" };

if (word.Any(input.Contains))
{
//and here I want find left and right word from found words
}


So in desired result each found word must be attached as separate value, and should looks like this:

Found: all
Left: (NONE)
Right: our

Found: they
Left: trapped.
Right: recirculate

Found: they
Left: to
Right: offices

Jim Jim
Answer

Working example: https://ideone.com/hLry3u

string input = "all our vidphone lines here are trapped. they recirculate the call to other offices within the building";

var queryList = new List<string> { "other", "they", "all", "building" };

string[] stack = input.Split(' ');

foreach (var word in queryList)
{
    for (int i = 0; i < stack.Length; i++)
    {
        if (word != stack[i]) continue;

        Console.WriteLine($"Found: {word}");
        Console.WriteLine(i > 0 ? $"Left: {stack[i-1]}" : "Left: (NONE)");
        Console.WriteLine(i < stack.Length - 1 ? $"Right: {stack[i+1]}" : "Right: (NONE)");
        Console.WriteLine();
    }
}

Console.ReadLine();