2015-01-10 37 views
2

我需要从字符串数组中打印出字符串,该字符串数组中出现的特定字符数最多。在字符串数组中输出出现特定字符的大部分字符串

例子:

{"I","have","feelings"} , 'e'打印 “感情”。

{"doodlidoo","foo","moon"} , 'o'打印“doodlidoo”。

到目前为止,我已经想出了这个,它发现每个字符串的长度。我只需要弄清楚如何打印单个字符串。

public static String MostLettersInWord(String[] list, char c) 
{ 
    for (int x = 0; x < list.Length; x++) 
    { 
     int count = list[x].Split(c).Length - 1; 
    } 
    return list[0]; 
} 

回答

0

有这样做的方法很多,但通过自己的方式去和保持它的简单和基本的,只是在这里补充的比较功能

string answer; 
int prevCount = 0, count = 0; 
for (int x = 0; x < list.Length; x++) 
{ 
    int count = list[x].Split(c).Length - 1; 
    if(count>prevCount) 
    { 
     answer = list[x]; 
     prevCount = count; 
    } 


} 
return answer; 
+0

谢谢,这并获得成功:) – Egon

0

你可以用LINQ轻松地做到这一点:

string result = list.OrderByDescending(str => str.Max(m => m == c)).First(); 
1

试试这个: -

var word = words.OrderByDescending(x => x.Count(z => z == c)).First(); 

Working Fiddle

0

想寻找具有特定字符相同的最大数量的所有单词下面的查询将选择他们:

List<string> words = new List<string> { "I", "have", "feelings", "meet" }; 

char ch = 'e'; 
var results = 
    words 
    .Where(w => w.Contains(ch)) 
    .Select(w => new 
    { 
     Word = w, 
     CharCount = w.Count(c => c.Equals(ch)) 
    }) 
    .OrderByDescending(x => x.CharCount) 
    .GroupBy(x => x.CharCount) 
    .First() 
    .Select(x => x.Word) 
    .ToList(); 
相关问题