私が取り組んでいる小さなコンソール アプリケーションがあり、実際の単語数ではなく、いくつかの 0 を返します。また、スペースを数えているため、ロジックに欠陥があることに気付きました。これは通常、文字列の最後の単語をカウントしません。私のコードを修正する方法に関する提案。ありがとう。
static void Main()
{
bool fileExists = false;
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = filePath + @"\wordcount.txt";
fileExists = File.Exists(file);
if (fileExists)
{
Console.WriteLine("{0} contains the following", file);
Console.WriteLine(File.ReadAllLines(file));
foreach (char words in file)
{
int stringCount = 0;
if (words == ' ')
{
stringCount++;
}
Console.WriteLine(stringCount);
}
}
else
{
Console.WriteLine("The file does not exist, creating it");
File.Create(file);
}
Console.ReadLine();
}
ファイルパスではなく内容をチェックするように編集しました(ここではnoobがnoobの間違いを犯しています)。foreach ループ内の if ステートメントを使用したロジックが悪いように感じます。
if (fileExists)
{
Console.WriteLine("{0} contains the following", file);
string[] contents = File.ReadAllLines(file);
foreach (string words in contents)
{
int stringCount = 0;
if (words == " ")
{
stringCount++;
}
Console.WriteLine(stringCount);
}
}