简体   繁体   English

如何计算C#文件中的字符数?

[英]how to count number of characters in a file in C#?

I tried 我试过了

    string str1 = File.ReadAllText("D:\\this.txt");
    str1.Length;
    byte[] fileBytes = File.ReadAllBytes("D:\\this.txt");
    fileBytes.Length;

gone thru similar question but each time same problem arises, it counts carriage return and new line also like in my file data is 经历了类似的问题,但是每次出现相同的问题时,它都会计算回车和换行,就像我的文件数据中一样

123
456
7 

it is showing '11' but output should be '7' help needed EDIT: i want to count every element which have ASCII greater than or equal to 32 它显示为“ 11”,但输出应为“ 7”。需要帮助:编辑:我想计算ASCII大于或等于32的每个元素

You could load all lines, then add all the lengths of each line together using linq: 您可以加载所有行,然后使用linq将每行的所有长度加在一起:

var numberOfCharacters = File.ReadAllLines(@"D:\this.txt").Sum(s => s.Length);

Alternative 另类

Doesn't count whitespace except space or controls chars. 除空格或控制字符外,不计算空格。 Requirements are fuzzy, but should put you on right track. 需求是模糊的,但应该使您走上正轨。

 var numberOfCharacters = File.ReadAllText(@"D:\this.txt").
    Count(c => c==" " ||
    (!Char.IsControl(c) &&
     !Char.IsWhiteSpace(c)));

Well character count will always (and should always) count non-visible characters because they are still characters. 那么字符数将永远(并应始终),因为他们仍然指望字符不可见的字符。 You can look on the MSDN for what qualifies as a whitespace character and use Replace . 您可以在MSDN上查找符合空格字符的字符,然后使用Replace

I would like to make note that, although the other responses will work, they're neglecting the fact that carriage return and line-feed are not the only non-visible whitespace characters you will encounter. 我想指出的是,尽管其他响应也可以使用,但它们忽略了回车和换行不是您将遇到的唯一不可见空白字符的事实。 And different OS's will handle "Enter" or "Return" differently. 并且不同的操作系统将以不同的方式处理“输入”或“返回”。 Some with just \\n and others with '\\r\\n'. 有些只有\\n ,有些只有'\\ r \\ n'。

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

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