C#无论如何都要获取包含语句的值

时间:2017-09-29 15:31:12

标签: c# arrays

我有这个

String[] greet = "hi","hello","hey";
String match;
String sen = "hi, how are you?";
if(sen.contains(greet[]))
{
       //get the "hi" from the sen.
       Match = //the matching words           
}

我必须找到一种方法来获得包含语句匹配的单词。

4 个答案:

答案 0 :(得分:3)

使用linq' s .Where来获取匹配的单词集合:

string[] greet = new string[] { "hi", "hello", "hey" };
string sen = "hi, how are you?";

List<string> matches = greet.Where(w => sen.Contains(w)).ToList();

答案 1 :(得分:0)

可能更容易使用foreach语句并循环遍历问候,然后通过空格(即"")拆分sen,因此您有两个数组。然后,您可以检查您的值是否匹配。

答案 2 :(得分:0)

您可能希望句子拆分为单词(让我们将单词描述为非空字母或/和撇号序列 - [\w']+ ):

  String sen = "hi, how are you?";

  // ["hi", "how", "are", "you"]
  String[] words = Regex
    .Matches(sen, @"[\w']+")
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

然后过滤掉Greet中的所有字词:

  HashSet<string> greet = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { 
    "hi", "hello", "hey" };

  List<string> matches = words
    .Where(word => greet.Contains(word))
    .ToList();

或者如果我们将两个部分结合起来:

  HashSet<string> greet = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { 
    "hi", "hello", "hey" };

  List<string> matches = Regex
    .Matches(sen, @"[\w']+")
    .OfType<Match>()
    .Select(match => match.Value)
    .Where(word => greet.Contains(word))
    .ToList();

请注意,当我们要执行HashSet<T>时,T[]通常比Contain更方便。

答案 3 :(得分:0)

List<string> greet = new List<string>(){ "hi", "hello", "hey" };
List<string> matches;
string sentence = "hi, how are you?";
matches = greet.FindAll(g => sentence.Contains(g));
foreach (var match in matches)
    Console.WriteLine(match);