簡體   English   中英

C# 檢查字符串中的特定單詞是否等於數組中的任何單詞

[英]C# check if specific word in string is equal to any word in array

我正在嘗試檢查字符串中的某個單詞是否等於數組中的任何字符串

正如你所知道的,我嘗試做的事情不起作用。

string[] friends = new string[3] {"bob", "greg", "jeb"};
if("does bob like cake?" == $"does {friends} like cake?") {
    Console.WriteLine("yes, he does");
}
else {
    Console.WriteLine("i don't know who that is");
}

有沒有辦法做到這一點而不必遍歷數組中的每個字符串?

一種或另一種方式,你需要檢查所有的項目,直到你得到一個真實的。 為此,您可以使用Any

string[] friends = new string[3] {"bob", "greg", "jeb"};
if(friends.Any(f => "does bob like cake?" == $"does {f} like cake?")) {
    Console.WriteLine("yes, he does");
}
else {
    Console.WriteLine("i don't know who that is");
}

現場示例: https://dotnetfiddle.net/4BldBo

您需要檢查您的特定朋友姓名是否包含在列表中,為此有一個方法“包含”。

string[] friends = new string[3] {"bob", "greg", "jeb"};
var friendName = "bob";
if (friends.Contains(friendName)) {
{
   Console.WriteLine("yes, he does");
}
else {
   Console.WriteLine("i don't know who that is");
}

如果您知道,您的朋友姓名(在本例中為 bob)始終是字符串中的第二個單詞,那么您可以這樣做

var question = "does bob like cake?";
var questionArray = question.Split(); // Split by white space
var friendName = questionArray[1]; // Get the name of your friend
if (friends.Contains(friendName)) {
{
   Console.WriteLine("yes, he does");
}
else {
   Console.WriteLine("i don't know who that is");
}

從字符串中取出單詞並將其與其他數組成員進行比較可能會有所幫助。

string[] friends = new string[3] {"bob", "greg", "jeb"};
var secondWord = str.Split(' ')[1];
foreach(var friend in friends)
{
if(secondWord == friend) {
    Console.WriteLine("yes, he does");
}
else {
    Console.WriteLine("i don't know who that is");
}    
}

假設他知道要檢查哪個詞,因為他說的是“某個詞”而不是“任何詞”,那么以下 function 可能會起作用:

void CheckString(string stringToCheck, string[] friends, int indexOfWordToCheck)
{
   var delimiters = new [] {' ', '.', ',', ':', ';', '?', '!'};  
   if(friends.Contains(stringToCheck.Split(delimiters)[indexOfWordToCheck]))
   {  
      Console.WriteLine("yes, he/she does!");
   }
   else
   {
      Console.WriteLine("who is that?");
   }
}

用法:

CheckString("Does bob like cake?", new [] { "bob", "greg", "jeb" }, 1);

是的,使用 LINQ 您可以比較兩個 arrays,這意味着算法在找到相同值的元素時會停止。

string[] friends = new string[3] {"bob", "greg", "jeb"};
string str = "Does bob like cake ?";

if(friends.Intersect(str.Split(' ')).Any())
{
    Console.WriteLine("Yes");
}

感謝如何檢查一個數組是否包含另一個數組的任何項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM