在字符串数组中打印出特定字符出现次数最多的字符串
Printing out the string with most occurences of a specific char, in a string array
我需要从一个字符串数组中打印出字符串,该数组中特定字符的出现次数最多。
示例:
{"I","have","feelings"} , 'e'
打印 "feelings".
{"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];
}
有很多方法可以做到这一点,但是按照您的方式并保持简单和基本,只需在此处添加比较功能
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;
您可以使用 LINQ 轻松完成:
string result = list.OrderByDescending(str => str.Max(m => m == c)).First();
试试这个:-
var word = words.OrderByDescending(x => x.Count(z => z == c)).First();
如果您要查找具有相同最大特定字符数的所有单词,以下查询将 select 它们:
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();
我需要从一个字符串数组中打印出字符串,该数组中特定字符的出现次数最多。
示例:
{"I","have","feelings"} , 'e'
打印 "feelings".
{"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];
}
有很多方法可以做到这一点,但是按照您的方式并保持简单和基本,只需在此处添加比较功能
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;
您可以使用 LINQ 轻松完成:
string result = list.OrderByDescending(str => str.Max(m => m == c)).First();
试试这个:-
var word = words.OrderByDescending(x => x.Count(z => z == c)).First();
如果您要查找具有相同最大特定字符数的所有单词,以下查询将 select 它们:
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();