输入一个单词时,我试图显示相同元音的总数。例如:芝士蛋糕。 元音总数为5(e,e,e,a,e),而相同的元音总数(即“ e”)为4。 我做的代码仍然显示相同元音的数量为5。 我的代码有问题吗?
static void Main()
{
Console.Write("Enter a word or phrase : ");
string input = Console.ReadLine();
char[] listOfVowels = new char[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
int vowel = 0;
int sameVowel = 0;
for (int i = 0; i < input.Length; i++)
{
if (listOfVowels.Contains(input[i]))
{
Console.WriteLine(input[i]);
vowel++;
if(input[i] == input[i])
{
sameVowel++;
}
}
}
Console.WriteLine($"The total number of vowel are : {vowel}");
Console.WriteLine($"The total of the same number of vowel are : {sameVowel}");
}
元音总数:5 元音相同的总数是:5
答案 0 :(得分:0)
您的代码可以简化:
static void Main()
{
Console.Write("Enter a word or phrase : ");
string input = Console.ReadLine()/*"cheesecake"*/;
char[] listOfVowels = new char[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
int vowel = 0;
vowel = input.Count(z => listOfVowels.Contains(z));
var sameVowelPair = input.Where(c => listOfVowels.Contains(c)).GroupBy(c => c).ToDictionary(s1 => s1.Key, s1=> s1.Count()).OrderByDescending(w => w.Value).FirstOrDefault();
Console.WriteLine($"The total number of vowel are : {vowel}");
Console.WriteLine($"The total of the same number of vowel are : {sameVowelPair.Value}");
}
输出:
答案 1 :(得分:0)
您可以尝试以下代码,创建一个存储元音的列表,并使用linq来计数相同的元音
static void Main(string[] args)
{
Console.Write("Enter a word or phrase : ");
string input = Console.ReadLine();
char[] listOfVowels = new char[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
int vowel = 0;
int sameVowel = 0;
List<char> vowers = new List<char>();
for (int i = 0; i < input.Length; i++)
{
if (listOfVowels.Contains(input[i]))
{
Console.WriteLine(input[i]);
vowel++;
vowers.Add(input[i]);
//if(vowers.Contains(input[i]))
//{
// sameVowel++;
//}
}
}
sameVowel = vowers.GroupBy(_ => _).Where(_ => _.Count() > 1).Sum(_ => _.Count());
Console.WriteLine(string.Format("The total number of vowel are : {0}", vowel));
Console.WriteLine(string.Format("The total of the same number of vowel are : {0}", sameVowel));
Console.ReadLine();
}
答案 2 :(得分:0)
遵循OOP和“单一职责原则”的基础,您可以将此逻辑封装到一个类中,该类将为您处理此逻辑
课程
public class VowelStatistics
{
private readonly string word;
public VowelStatistics(string word)
{
this.word = word;
}
public IEnumerable<char> Vowels => word.Where(c => "aeiouAEIOU".Contains(c));
public int VowelCount => Vowels.Count();
public char MostFrequentVowel => Vowels
.GroupBy(c => c)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.First();
public int MostFrequentVowelCount => Vowels
.GroupBy(c => c)
.Max(g => g.Count());
// Adding this as per @Everyone's comment, which will give you vowel groupings by frequency.
public IEnumerable<IGrouping<char, char>> VowelsByFrequency => Vowels
.GroupBy(c => c)
.OrderByDescending(g => g.Count());
}
用法
VowelStatistics vs = new VowelStatistics("cheesecake");
结果
vs.Vowels = {'e','e','e','a','e'}
vs.VowelCount = 5
vs.MostFrequentVowel ='e'
vs.MostFrequentVowelCount = 4
答案 3 :(得分:-1)
看看这个(不涉及LINQ):
static (int, char, int) vowelStats(string str)
{
// VOWEL ONLY DICTIONARY
Dictionary<char, int> counts = new Dictionary<char, int>()
{
{'a', 0} , { 'e', 0} , { 'i', 0} , { 'o', 0} , { 'u', 0}
};
int vowels = 0;
char high = '\0';
foreach(char c in str)
{
char c1 = Char.ToLower(c); // convert letter to lowercase first
// if dictionary has the character, then it must be a vowel
if (counts.ContainsKey(c1))
{
counts[c1]++; // vowel itself count
vowels++; // total vowel count
if (!counts.ContainsKey(high)) high = c1; // will only be true once
if(vowels - counts[c1] < vowels - counts[high]) // update current most frequent
high = c1;
}
}
if(!counts.ContainsKey(high)) // if no vowels found, high will be '\0'
return (0, '\0', 0);
return (vowels, high, counts[high]);
}
static void Main(string[] args)
{
Console.Write("Enter a word or phrase : ");
string input = Console.ReadLine();
int vowels, mostFrequentVowelCount;
char mostFrequenctVowel;
(vowels, mostFrequenctVowel, mostFrequentVowelCount) = vowelStats(input);
Console.WriteLine("Total number of vowels: {0}", vowels);
Console.WriteLine("Most frequent vowel: {0}", mostFrequenctVowel);
Console.WriteLine("Most frequent vowel count: {0}", mostFrequentVowelCount);
}
输出:
输入单词或短语:芝士蛋糕
元音总数:5
最常见的元音:e
最常见的元音计数:4
注意:
1)我假设您所说的“相同元音”是“最频繁的元音”。
2)该代码仅在.Net Framework 4.7或更高版本(元组函数)或.Net Core 2或更高版本中有效。
3)时间复杂度:O(N),其中N是字符串中的字符数。
4)空间复杂度:O(C),其中C是一个常数,表示字典中元音及其相应整数的数量,以及其他几个变量。
5)如果两个元音频率最高,此功能将选择最先遇到的一个。也就是说,在“ woohee”的情况下将是“ o”,在“ weehoo”的情况下将是“ e”。
6)我更新了代码,因此它不关心大写/小写。如果遇到元音而不管大小写如何,它将更新一个且只有一个计数器。
7)这不使用任何LINQ,对于基本的C#应该足够简单。我之所以不使用LINQ,是因为它增加了复杂性和性能开销。
答案 4 :(得分:-1)
这对我来说很简单:
string input = "cheesecake";
var query =
from v in "aeiouAEIOU"
join c in input on v equals c
group c by c into gcs
orderby gcs.Count() descending
select gcs;
Console.WriteLine($"Vowels: {String.Join(", ", query.SelectMany(c => c))}");
Console.WriteLine($"Most Frequent Vowel: {query.First().Key}");
Console.WriteLine($"Most Frequent Vowel Count: {query.First().Count()}");
给出:
Vowels: e, e, e, e, a Most Frequent Vowel: e Most Frequent Vowel Count: 4
性能测试代码:
static (int, char, int) vowelStatsPlain(string str)
{
// VOWEL ONLY DICTIONARY
Dictionary<char, int> counts = new Dictionary<char, int>()
{
{'a', 0} , { 'e', 0} , { 'i', 0} , { 'o', 0} , { 'u', 0}
};
int vowels = 0;
char high = '\0';
foreach (char c in str)
{
char c1 = Char.ToLower(c); // convert letter to lowercase first
// if dictionary has the character, then it must be a vowel
if (counts.ContainsKey(c1))
{
counts[c1]++; // vowel itself count
vowels++; // total vowel count
if (!counts.ContainsKey(high)) high = c1; // will only be true once
if (vowels - counts[c1] < vowels - counts[high]) // update current most frequent
high = c1;
}
}
if (!counts.ContainsKey(high)) // if no vowels found, high will be '\0'
return (0, '\0', 0);
return (vowels, high, counts[high]);
}
static (int, char, int) vowelStatsLinq(string str)
{
var query =
(
from v in "aeiouAEIOU"
join c in str on v equals c
group c by c into gcs
orderby gcs.Count() descending
select gcs
).ToArray();
var first = query.First();
return (query.SelectMany(c => c).Count(), first.Key, first.Count());
}
static void Main(string[] args)
{
string input = "The information contained in this email is confidential and for the addressee only; If you are not the intended recipient of this email, please reply and let us know that an incorrect address may have been used. If you do not wish to be communicated with by email, please respond so that we may remove your address from our records. Your co-operation is appreciated.";
Func<TimeSpan> callPlain = () =>
{
var sw = Stopwatch.StartNew();
(int vowels, char mostFrequenctVowel, int mostFrequentVowelCount) = vowelStatsPlain(input);
sw.Stop();
return sw.Elapsed;
};
Func<TimeSpan> callLinq = () =>
{
var sw = Stopwatch.StartNew();
(int vowels, char mostFrequenctVowel, int mostFrequentVowelCount) = vowelStatsLinq(input);
sw.Stop();
return sw.Elapsed;
};
var trials = Enumerable.Range(0, 1000000).Select(x => new { plain = callPlain(), linq = callLinq() }).ToArray();
Console.WriteLine(trials.Skip(2).Average(x => x.plain.TotalMilliseconds));
Console.WriteLine(trials.Skip(2).Average(x => x.linq.TotalMilliseconds));
Console.WriteLine(trials.Skip(2).Average(x => x.linq.TotalMilliseconds) / trials.Skip(2).Average(x => x.plain.TotalMilliseconds));
}