Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在字符串数组中打印出现最多特定字符的字符串_C#_Arrays_String_Loops - Fatal编程技术网

C# 在字符串数组中打印出现最多特定字符的字符串

C# 在字符串数组中打印出现最多特定字符的字符串,c#,arrays,string,loops,C#,Arrays,String,Loops,我需要从一个字符串数组中打印出字符串,该数组中出现的特定字符最多 示例: {“我”、“有”、“感觉”},“e”打印“感觉” {“doodlido”、“foo”、“moon”},“o”打印“doodlido” 到目前为止,我已经找到了这个,它可以找到每个字符串的长度。我只需要弄清楚如何打印单个字符串 public static String MostLettersInWord(String[] list, char c) { for (int x = 0; x < list.Le

我需要从一个字符串数组中打印出字符串,该数组中出现的特定字符最多

示例:

{“我”、“有”、“感觉”},“e”打印“感觉”

{“doodlido”、“foo”、“moon”},“o”打印“doodlido”

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

 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];
 }
公共静态字符串MostLettersInWord(字符串[]列表,字符c)
{
for(int x=0;x
有很多方法可以做到这一点,但按照您的方式,并保持简单和基本,只需在此处添加一个比较功能即可

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;
字符串应答;
int prevCount=0,count=0;
for(int x=0;x上一计数)
{
答案=列表[x];
prevCount=计数;
}
}
返回答案;

使用LINQ,您可以轻松完成此任务:

string result = list.OrderByDescending(str => str.Max(m => m == c)).First();
试试这个:-

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

.

如果要查找具有相同最大特定字符数的所有单词,以下查询将选择它们:

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();
List words=新列表{“我”、“有”、“感觉”、“相遇”};
char ch='e';
var结果=
话
其中(w=>w.Contains(ch))
.选择(w=>new
{
Word=w,
CharCount=w.Count(c=>c.Equals(ch))
})
.OrderByDescending(x=>x.CharCount)
.GroupBy(x=>x.CharCount)
.First()
.选择(x=>x.Word)
.ToList();