我希望能夠使用 Visual Studio 計算 C# 中的名字和姓氏。目前我只能在文本中搜索 1 個單詞。我正在使用 .NET 5.0(當前)創建控制臺應用程式。
(當輸入是“哈利”時,它計算哈利被找到的次數,當輸入是“哈利波特”時,即使文本中多次出現“哈利波特”,它也總是計算為 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");
}
}
}
uj5u.com熱心網友回復:
也許,根據 Auditive 的建議:
int count = System.Text.RegularExpressions.Regex.Matches(text, input, RegexOptions.IgnoreCase).Count
如果您仍然很矮,請更改 input 使其具有 value harry\s potter,\s 意思是“至少一個空格”,以防萬一您的文本有harrySPACESPACEpotter.. (歡迎來到正則運算式的奇妙而神秘的世界)
如果您仍然很矮,我認為您可能在檔案中有拼寫錯誤!??
——
如果你想數哈利或波特,你可以調整你的正則運算式為harry|potter..
——
存在解決此挑戰的其他方法,典型的方法是檢查通過拆分獲得的陣列的長度:
int count = text.Split(input).Length - 1;
如果有 5 個哈利波特,你會從 Split 中得到一個 6 長的陣列,因此是 -1。不過,這可能會占用更多資源;如果您追求盡可能低的 CPU 消耗,您可能會看到以下內容:
int count=0;
for(int idx = text.IndexOf(input); idx > -1; count , idx = text.IndexOf(input, idx input.Length));
這將設定一個用于計數的變數,然后重復使用 IndexOf,直到它回傳 -1。每次在第一次之后,IndexOf 從上次找到的字串的末尾開始。沒有回圈體,一切都發生在標題中。
值得指出的是,這些都不區分大小寫,但可以通過更多的作業來做到這一點
uj5u.com熱心網友回復:
您可以使用正則運算式和 File.ReadLines("File.txt") 在這里您可以看到它: count a specific word in a text file in C#
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333942.html
標籤:C#
