2012-04-02 121 views
1

我想要做的事情非常簡單。用戶輸入一個字符串。該程序檢查並計算該文本字符串中存在的元音數量。C# - 比較兩個數組中的值

如何檢查2個數組以查看是否有任何匹配?

謝謝。

回答

3

您可以使用Array.IndexOf()此:

if (Array.IndexOf(vowels, i) >= 0) 
{ 
    // the character is present 
} 
1

我會使用LINQ:

arr.Select(c => vowels.Contains(c)); 

爲了得到字符數,您可以使用Count方法,而不是Select。 如果你想知道是否有元音,那麼使用Any - 只要找到第一個匹配就會終止。

+0

我在LINQ沒有知識的,因爲現在我在初學階段,我只是學習,如果C#。但是,感謝那些信息。我會記住這一點。這似乎更容易。 – Isuru 2012-04-02 08:01:40

6
arr.Any(p => vowels.Contains(p)); 

更新: 要計算可能使用的匹配數量;

int count = arr.Where(p => vowels.Contains(p)).Count(); 
+0

_count_在哪裏? – 2012-04-02 07:47:21

+0

在問題計數沒有問,但你可能會發現使用int count = arr.Where(p => vowels.Contains(p))。計數(); – daryal 2012-04-02 07:50:52

+0

問題要求計數:**程序檢查並計算元音數量** – fearofawhackplanet 2012-04-02 08:06:15

0

你可以做的是創造元音字符的列表,然後使用.contains方法。

1

試試這個:

if (vowels.Contains(i)) 
{ 
    counter++; 
} 
0

您可以使用LINQ爲!

bool anyMatches = arr.Intersect(vowels).Any(); 

,或者,如果你想要的比賽:

var matches = arr.Intersect(vowels).ToList(); 

編輯:

或數匹配的確切數目:

int count = arr.Count(x => vowels.Contains(x)); 
+0

這個計數不同元音的數量,不是元音的總數(「woot」產生一個'o') – 2012-04-02 07:51:24

+0

這是一個問題?? – 2012-04-02 07:51:59

+0

是的,看看提交的代碼 - 對於arr中的每個角色,他想檢查另一個數組以查找匹配。 – 2012-04-02 07:56:03

2

只需用兩個foreach迴圈

foreach(var i in arr) 
    { 
     foreach(var j in vowels) 
     { 
      if(i==j) 
      { 
       counter++; 
      } 
     } 
    } 
0

使用此LINQ查詢

var q=from c in s 
    where vowels.Contains(c) 
    group c by c into g 
    select new {vowel=g.Key, count=g.Count()}; 

那麼你可以重複做什麼,你的內容

例如喜歡

foreach (var x in q) { 
    Console.WriteLine(String.Format("{0} : {1}",x.vowel,x;count)); 
} 
0
Hash<char> vowels = //initialize to vowels. 

foreach(char c in input) 
{ 
    if(hashset(vowels) contains the character) 
     increment counter. 
} 

return counter.