有没有办法修改此循环?

时间:2020-02-21 04:57:58

标签: c#

因此,我试图通过此代码测试用户输入的单词中是否包含某些字母,并确定该用户输入中有多少特定字母。

如果我输入单词aCounter,则bCounter的得分为4,"aabb"的得分为4。

我如何做到这一点,例如,如果有2个a,并且已经对"a"进行了2次测试,则测试字母"a"循环就会停止。 / p>

static int aCounter, bCounter;

public static void Main (string[] args)
{
    Console.Write("Enter the secret word: ");
    string word = Console.ReadLine();

    for(int i = 0; word.Length > i; i++)
    {       
        if (word.Count(letter => letter == 'a') > 0)
        {
            Console.WriteLine("\nThe word contains a");
            aCounter++;
        }

        if (word.Count(letter => letter == 'b') > 0)
        {
            Console.WriteLine("\nThe word contains b");
            bCounter++;
        }

        if (aCounter > 0)
        {
            Console.WriteLine(aCounter);
        }

        if (bCounter > 0)
        {
            Console.WriteLine(bCounter);
        }
}

1 个答案:

答案 0 :(得分:7)

您似乎正在将 linq 循环

我想这与您想要的内容更加内联(只需删除循环)

Console.Write("Enter the secret word: ");
string word = Console.ReadLine();

aCounter = word.Count(letter => letter == 'a');
bCounter = word.Count(letter => letter == 'b');

if (aCounter > 0)
   Console.WriteLine($"The word contains a : {aCounter}");

if (bCounter > 0)
   Console.WriteLine($"The word contains b : {bCounter}");

输出

Enter the secret word: aabb
The word contains a : 2
The word contains b : 2

您还可以算出所有字符出现,并将它们放入字典中,然后进行明确测试

var letters = word.GroupBy(x => x)
                  .ToDictionary(x => x.Key, x => x.Count());

if (letters.TryGetValue('a', out var aCount))
   Console.WriteLine($"The word contains a : {aCount}");

if (letters.TryGetValue('a', out var bCount))
   Console.WriteLine($"The word contains b : {bCount}");