如何在搜索词的左边和右边找到单词

本文关键字:右边 单词 左边 搜索 | 更新日期: 2023-09-27 18:15:31

如何在字符串中找到左和右单词从选定的单词字符串可能包含,例如我有一个字符串:

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 
}

所以在期望的结果中,每个找到的单词必须作为单独的值附加,并且应该看起来像这样:

Found:   all 
Left:    (NONE)
Right:   our
Found:   they 
Left:    trapped.
Right:   recirculate
Found:   they 
Left:    to
Right:   offices

如何在搜索词的左边和右边找到单词

拆分input字符串

String[] haystack = input.Split(' ');

对于查询中的每个单词,在haystack

上进行搜索
foreach (var w in word) {
     for (int i = 0; i < haystack.Length; i++) {
         if (w == haystack[i]) {
             // print w
             // left is haystack[i-1] when i > 0, if i == 0 it's None
             // right is haystack[i+1] when i < haystack.length-1, if i == haystack.length-1 it's None
         }
     }
}

示例: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(' ').Select(s => s.Trim())
                                 .Where(s => s != string.Empty)
                                 .ToArray();
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();

也可以使用

string[] stack = Regex.Split(input, @"'s+");

代替

string[] stack = input.Split(' ').Select(s => s.Trim())
                                 .Where(s => s != string.Empty)
                                 .ToArray();

取决于你喜欢的RegEx