2016-10-29 1 views
1

の左右の単語が含まれていてもよい見つけるために、例えば、私は、文字列を持っている:どのように選択した単語列から文字列の左と右の単語を見つけることができますどのように検索語

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 

答えて

0

上で検索を実行します。また、あなたが

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

代わりの

string[] stack = input.Split(' ').Select(s => s.Trim()) 
           .Where(s => s != string.Empty) 
           .ToArray(); 
を使用することができます 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(); 

あなたの好みに応じてRegEx

+1

こんにちは、これは実装であり、正確に尋ねられる出力を表示するので、私はこの答えに印を付けるつもりですが、下の@esceptaの回答は同じ結果を与えるので、サポートのおかげで –

+0

も小さな編集をしました...この例では本当に必要ではありませんが、空のエントリがあるかどうかを確認して削除することができます(単語間に二重スペースがあることが原因です) – Jim

+0

はい必要であり、一般的に非常に有用な解決策 –

1

スプリットinput文字列

String[] haystack = input.Split(' '); 
:望ましい結果各単語が個別の値として添付しなければならない見つけ、とすべきは、このようになります。クエリ内の各単語に対して

、例の作業干し草の山

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 
     } 
    } 
} 
関連する問題