简体   繁体   English

计算文件的总字符数

[英]Counting total characters of a file

Hi I'm pretty new to C# and trying to do some exercises to get up to speed with it.嗨,我对 C# 很陌生,并尝试做一些练习以跟上它的速度。 I'm trying to count the total number of characters in a file but it's stopping after the first word, would someone be able to tell me where I am going wrong?我正在尝试计算文件中的字符总数,但它在第一个单词后停止,有人能告诉我哪里出错了吗? Thanks in advance提前致谢

 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);


        }

If you want to know the size of a file:如果您想知道文件的大小:

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

If you want to count characters to play around with C#, then here is some sample code that might help you如果您想计算字符以使用 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}");

it's stopping after the first word它在第一个单词之后停止

It is because you have check && i < l in the loop and then increment it so the check doesn't pass you don't change the value of l variable(by the way, the name is not very good, I was sure it was 1 , not l ).这是因为您在循环中检查了&& i < l然后将其递增,因此检查不通过您不会更改 l 变量的值(顺便说一下,名称不是很好,我确定是1 ,而不是l )。

Then if you need to get total count of characters in the file you could read the whole file to a string variable and just get it from Count() Length然后,如果您需要获取文件中的字符总数,您可以将整个文件读取到一个字符串变量中,然后从 Count() Length 中获取它

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

Getting Length property of the FileInfo will give the size, in bytes, of the current file , which is not necessary will be equal to characters count(depending on Encoding a character may take more than a byte)获取 FileInfo 的 Length 属性将给出当前文件的大小(以字节为单位) ,这不是必需的,将等于字符数(取决于编码字符可能需要超过一个字节)

And regarding the way you read - it also depends whether you want to count new line symbols and others or not.关于您阅读的方式 - 这还取决于您是否要计算新行符号和其他符号。

Consider the following sample考虑以下示例

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();
}

For the second sample, first, the Length will return 3, because it actually contains three symbols, while with stream reader you will get 1, because The string that is returned does not contain the terminating carriage return or line feed.对于第二个示例,首先,长度将返回 3,因为它实际上包含三个符号,而使用 stream 阅读器您将得到 1,因为返回的字符串不包含终止的回车符或换行符。 The returned value is null if the end of the input stream is reached 如果到达输入 stream 的结尾,则返回值为 null

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

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