C#中的换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16017077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:44:01  来源:igfitidea点击:

New line character in c#

c#newline

提问by Ammar Alyousfi

I wrote this code to count the number of characters in a text file :

我写了这段代码来计算文本文件中的字符数:

sr.BaseStream.Position = 0;
sr.DiscardBufferedData();
int Ccount = 0;
while (sr.Peek() != -1)
{
  sr.Read();
  Ccount++;
}

but after applying this code to a file contains :

但是在将此代码应用于包含以下内容的文件后:

1
2
3
4
5
6
7
8
9
0

Ccount = 30 ???? why? I am using Windows Xp on virtual box on my Macbook the program used : Microsoft Visual Basic 2010.

帐号 = 30 ???? 为什么?我在我的 Macbook 上的虚拟机上使用 Windows Xp 使用的程序:Microsoft Visual Basic 2010。

采纳答案by Sina Iravanian

In Windows each new line consists of two characters \rand \n. You have 10 lines, each line have 1 visible characters and 2 new line characters which add up to 30 characters.

在 Windows 中,每个新行由两个字符\r\n. 你有 10 行,每行有 1 个可见字符和 2 个新行字符,加起来最多 30 个字符。

If you have created your file in Mac or Unix/Linux you would have gotton different result (20 characters). Because Unix uses only \nand Mac uses only \rfor a new line.

如果您在 Mac 或 Unix/Linux 中创建了文件,则会得到不同的结果(20 个字符)。因为 Unix 只使用\n而 Mac 只\r用于换行。

You can use some editors (such as Notepad++) to show you new line characters, or even switch between different modes (DOS/Unix/Mac).

您可以使用一些编辑器(例如 Notepad++)来显示换行符,甚至可以在不同模式之间切换(DOS/Unix/Mac)。

回答by RichieHindle

You're reading one character at a time, and each line contains three characters:

您一次读取一个字符,每行包含三个字符:

  • one digit
  • one carriage return (\r)
  • one newline (\n)
  • 一位数
  • 一个回车 ( \r)
  • 一个换行符 ( \n)

(Windows uses \r\nas its newline sequence. The fact that you're running in a VM on a Mac doesn't affect that.)

(Windows\r\n用作其换行符序列。您在 Mac 上的 VM 中运行这一事实不会影响它。)

回答by Zdravko Danev

The new line is actually 2 separate characters: LF CR (line feed and carriage return). But you would know that if you put a breakpoint in your loop. Now for extra credit, how many bytes that is in unicode?

新行实际上是 2 个单独的字符:LF CR(换行和回车)。但是你会知道,如果你在循环中放置一个断点。现在为了额外的功劳,unicode 中有多少字节?

回答by weston

Windows typically uses \r\nfor new line, that is ASCII characters 0x13 and 0x10.

Windows 通常用于\r\n换行,即 ASCII 字符 0x13 和 0x10。

Suggest you prove this to yourself by doing this:

建议您通过这样做来向自己证明这一点:

Console.WriteLine("0x{0:x}", sr.Read());

回答by Hjalmar Z

There's an easier way to do this. Make the entire *.txt file to a string array and measure it:

有一种更简单的方法可以做到这一点。将整个 *.txt 文件制作成字符串数组并进行测量:

int count = 0;

string[] Text = File.ReadAllLines(/*Path to the file here*/);

for (int i = 0; i < Text.Count(); i++)
{
        count += Text[i].Length;
}