繁体   English   中英

计算文件的总字符数

[英]Counting total characters of a file

嗨,我对 C# 很陌生,并尝试做一些练习以跟上它的速度。 我正在尝试计算文件中的字符总数,但它在第一个单词后停止,有人能告诉我哪里出错了吗? 提前致谢

 public void TotalCharacterCount()
        {
            string str;
            int count, i, l;
            count  = i = 0;

            StreamReader reader = File.OpenText("C:\\Users\\Lewis\\file.txt");
            str = reader.ReadLine();
            l = str.Length;


                while (str != null && i < l)
                {

                    count++;

                    i++;

                    str = reader.ReadLine();
                }



            reader.Close();
            Console.Write("Number of characters in the file is : {0}\n", count);


        }

如果您想知道文件的大小:

long length = new System.IO.FileInfo("C:\\Users\\Lewis\\file.txt").Length;
Console.Write($"Number of characters in the file is : {length}");

如果您想计算字符以使用 C#,那么这里有一些示例代码可能会对您有所帮助

            int totalCharacters = 0;

            // Using will do the reader.Close for you. 
            using (StreamReader reader = File.OpenText("C:\\Users\\Lewis\\file.txt"))
            {
                string str = reader.ReadLine();

                while (str != null)
                {
                    totalCharacters += str.Length;
                    str = reader.ReadLine();
                }
            }

            // If you add the $ in front of the string, then you can interpolate expressions 
            Console.Write($"Number of characters in the file is : {totalCharacters}");

它在第一个单词之后停止

这是因为您在循环中检查了&& i < l然后将其递增,因此检查不通过您不会更改 l 变量的值(顺便说一下,名称不是很好,我确定是1 ,而不是l )。

然后,如果您需要获取文件中的字符总数,您可以将整个文件读取到一个字符串变量中,然后从 Count() Length 中获取它

var count = File.ReadAllText(path).Count();

获取 FileInfo 的 Length 属性将给出当前文件的大小(以字节为单位) ,这不是必需的,将等于字符数(取决于编码字符可能需要超过一个字节)

关于您阅读的方式 - 这还取决于您是否要计算新行符号和其他符号。

考虑以下示例

static void Main(string[] args)
{
    var sampleWithEndLine = "a\r\n";
    var length1 = "a".Length;
    var length2 = sampleWithEndLine.Length;
    var length3 = @"a
".Length;

    Console.WriteLine($"First sample: {length1}");
    Console.WriteLine($"Second sample: {length2}");
    Console.WriteLine($"Third sample: {length3}");
    var totalCharacters = 0;
    File.WriteAllText("sample.txt", sampleWithEndLine);

    using(var reader = File.OpenText("sample.txt"))
    {
        string str = reader.ReadLine();

        while (str != null)
        {
            totalCharacters += str.Length;
            str = reader.ReadLine();
        }
    }

    Console.WriteLine($"Second sample read with stream reader: {totalCharacters}");

    Console.ReadKey();
}

对于第二个示例,首先,长度将返回 3,因为它实际上包含三个符号,而使用 stream 阅读器您将得到 1,因为返回的字符串不包含终止的回车符或换行符。 如果到达输入 stream 的结尾,则返回值为 null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM