0

我有一个正在处理的小型控制台应用程序,它返回几个 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();
    }

我已经对其进行了编辑,以便我检查内容而不是文件路径(这里的菜鸟犯了菜鸟错误)。我仍然觉得我在 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);
            }

        }
4

7 回答 7

3

String.SplitFile.ReadAllText是您应该查看的函数。

var count = File.ReadAllText(file).Split(' ').Count();
于 2013-08-07T19:43:05.553 回答
3

您不是在读取实际文件,而是在读取file您声明为filePath + @"\wordcount.txt";.

您只是将文件内容输出到控制台。您应该将结果分配File.ReadAllLines(file)给一个新变量(类型string[]:http: //msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx),然后运行它。

于 2013-08-07T19:44:21.400 回答
0

如果您将文件内容读取为字符串,则可以使用此代码来计算空格。您只需将该计数加 1 即可处理最后一个单词。

int count = strFileContents.Split(' ').Length - 1;
于 2013-08-07T19:44:58.843 回答
0

您可以使用字符串拆分

 if (fileExists)
        {
            Console.WriteLine("{0} contains the following", file);
            Console.WriteLine(File.ReadAllLines(file));
            var fileContent=File.ReadAllText();

           stringCount=fileContent.Split(new [] {' ','\n'},StringSplitOptions.RemoveEmptyEntries).Length;
        }
于 2013-08-07T19:45:09.100 回答
0
if (fileExists)
    {
        string fileString = File.ReadAllText(file);
        var words = fileString.Split(' ');
        int strCount = words.Count();
    }

将文件读入字符串,用空格分割,计算数组中的项目数。

于 2013-08-07T19:45:18.040 回答
0

我认为这应该符合您的格式:

List<string> allWords = new List<string>();
foreach (string words in file)
    {
      allWords += words;
    }

int wordCount = allWords.Length();

虽然,我认为@AlexeiLevenkov 还是更好......

于 2013-08-07T19:46:29.193 回答
0
Regex.Matches(File.ReadAllText(file), @"[\S]+").Count;
于 2013-08-07T19:46:38.287 回答