我有这个
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
}
我必须找到一种方法来获得包含语句匹配的单词。
答案 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();
string.Contains
检查给定字符串是否包含在另一个字符串中。如果您想要不区分大小写的搜索:Case insensitive 'Contains(string)' IEnumerable<T>.Where
返回集合的一个子集,其中仅包含与谓词匹配的项目 - 在这种情况下仅包含sen
答案 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);