我希望能够在C#中使用visual studio计算姓名和姓名。目前我只能在文本中搜索1个单词。我正在使用.NET 5.0 (当前版本)创建控制台应用程序。
(当输入为" Harry“时,它计算找到Harry的次数,当输入为"Harry Potter”时,即使文本中有多次出现的"Harry Potter“,它也始终计为0。)
我一直在谷歌上寻找答案,但只能找到如何计算1个单词。
下面是我当前的代码:
using System;
using System.IO;
namespace Harry
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
StreamReader stream = File.OpenText("Harry Potter and the Sorcerer.txt");
string text = stream.ReadToEnd();
string woord = "";
int count = 0;
foreach (var item in text)
{
if (Char.IsLetter(item))
{
woord = woord + item;
}
else
{
if(woord == input)
{
count++;
}
woord = "";
}
}
Console.Write(input + ": " + count + " occurrences");
}
}
}发布于 2021-10-23 11:59:00
您可以使用正则表达式和File.ReadLines("File.txt"),您可以在这里看到:count a specifc word in a text file in C#
https://stackoverflow.com/questions/69687840
复制相似问题