【问题标题】:How to Count Vowels in a sentence in Text File (C#)如何在文本文件中计算句子中的元音(C#)
【发布时间】:2013-10-11 00:07:23
【问题描述】:

我必须创建一个小程序,我必须提示用户输入习语并将它们存储到文本文件中。之后,我必须打开文本文件并计算每个成语(a、e、i、o、u)中单个元音的数量并将其显示给用户。

这是我目前创建的代码:

        int numberOfIdioms;
        string fileName = "idioms.txt";
        int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0;

        Console.Title = "String Functions";

        Console.Write("Please enter number of idioms: ");
        numberOfIdioms = int.Parse(Console.ReadLine());

        string[] idioms = new string[numberOfIdioms];
        Console.WriteLine();

        for (int aa = 0; aa < idioms.Length; aa++)
        {
            Console.Write("Enter idiom {0}: ", aa + 1);
            idioms[aa] = Console.ReadLine();
        }

        StreamWriter myIdiomsFile = new StreamWriter(fileName);

        for (int a = 0; a < numberOfIdioms; a++)
        {
            myIdiomsFile.WriteLine("{0}", idioms[a]);
        }

        myIdiomsFile.Close();

【问题讨论】:

  • 问题是什么?
  • 1.提示用户输入成语的数量并将它们写入一个名为“idioms.txt”的文件 2. 从 idioms.txt 文件中读取行并显示每个成语中的元音数
  • “作业”和“问题”不是一回事。
  • Google 关于 FileIO,因为这是一个非常基础的东西,你应该在课程中学习它。关于计数,只需使用针对元音的 switch 语句解析字符串中的每个字符(从 txt 文件中检索)。如果这没有意义,Google 会提供帮助!

标签: c# counting


【解决方案1】:

您可以使用以下代码获取字符串的元音计数:

int vowelCount = System.Text.RegularExpressions.Regex.Matches(input, "[aeoiu]").Count;

用你的字符串变量替换input

如果要不分大小写(大写/小写)计数,可以使用:

int vowelCount = System.Text.RegularExpressions.Regex.Matches(input.ToLower(), "[aeoiu]").Count;

【讨论】:

    【解决方案2】:

    string Target = "我的名字和你的名字未知 MY NAME AND YOUR NAME UNKNOWN";

    列表模式=新列表{'a','e','i','o','u','A','E','I','O','U'};

    int t = Target.Count(x => pattern.Contains(x));

    【讨论】:

      【解决方案3】:

      我们可以使用正则表达式来匹配每个 idoms 中的元音。 您可以调用下面提到的函数来获取元音计数。

      工作代码sn-p:

        //below function will return the count of vowels in each idoms(input)
       public static int GetVowelCount(string idoms)
         {
             string pattern = @"[aeiouAEIOU]+"; //regular expression to match vowels
             Regex rgx = new Regex(pattern);   
             return rgx.Matches(idoms).Count;
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        相关资源
        最近更新 更多