[英]A c# project! should i use String arrays? (is that even a thing?!)
I'm working on a program in c# where I'm supposed to tell the user to insert random characters and then divide those random characters into letters and numbers and count how many i have of each.我正在 c# 中开发一个程序,我应该告诉用户插入随机字符,然后将这些随机字符分成字母和数字,并计算我有多少。
anyone has any idea how to do so?有人知道怎么做吗? thanks: ps: i'm new to c# and programming alltogether :)谢谢:ps:我是 c# 和一起编程的新手 :)
You could use char.IsDigit
or char.IsNumber
to check if it's a "number"(digit):您可以使用char.IsDigit
或char.IsNumber
来检查它是否是“数字”(数字):
string input = Console.ReadLine();
int digitCount = input.Count(char.IsDigit);
int letterCount = input.Length - digitCount;
You need to add using System.Linq
to be able to use Enumerable.Count
.您需要添加using System.Linq
才能使用Enumerable.Count
。
Since you now have asked for counting vowels.由于您现在要求计算元音。 Vowels are a, e, i, o, u and their uppercase version.元音是 a、e、i、o、u 和它们的大写版本。 So you could use this method:所以你可以使用这个方法:
private static readonly HashSet<char> Vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
public static bool IsVowel(char c) => Vowels.Contains(c);
and this code to count the vowels:和这段代码来计算元音:
int vowelCount = input.Count(IsVowel);
If you don't just want to count them but show them to the user:如果您不仅想计算它们,还想将它们展示给用户:
string vowelsInInput = new String(input.Where(IsVowel).ToArray());
string noVowels = new String(input.Where(c => !IsVowel(c)).ToArray());
which also gives you the count(for example vowelsInInput.Length
).这也给你计数(例如vowelsInInput.Length
)。
Get the input and loop through every character within the string获取输入并遍历字符串中的每个字符
string testStr = "abc123";
foreach (char c in testStr)
{
Console.WriteLine(c.ToString( ));
}
You can use a dictionary to count the number of times a letter appears.您可以使用字典来计算字母出现的次数。
char letter = //your letter;
var charFrequencies = new Dictionary<char, int>();
if (!charFrequencies.ContainsKey(letter)) {
charFrequencies.Add(letter, 1);
}
else {
charFrequencies[letter]++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.