如何查找搜索到的单词左侧和右侧的单词

时间:2016-10-29 03:33:42

标签: c# string text

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

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

2 个答案:

答案 0 :(得分:1)

拆分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
         }
     }
}

答案 1 :(得分:0)

工作示例: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

的喜好