为什么换行符等于-1?

Why is the newline character equal to -1?

当我 运行 此代码 lineLength 返回为 -1 时,当我希望换行符位于文本行字符串的末尾并返回相应的值时.如果 \n 字符实际上在行的开头,那么如何找到行中最后一个字符的值?

我尝试通过将 lineLength 设置为 line.Length 来使用 .length,但是当我将 lineLength 作为 line.substring 中的长度参数时,我收到一条错误消息:

"index and length must refer to a location in the string"

int found;
int lineLength;
string[] lines = System.IO.File.ReadAllLines(
        @"C:\Program Files\C# Projects\Password Validation\UserAndPWSystem2\UPInfo.txt");

foreach (string line in lines)
{
    if (line.Contains("user number : "))
    {
        found = line.IndexOf(":");
        lineLength = line.IndexOf('\n');
        Console.WriteLine(lineLength);

        //Console.WriteLine(line.Substring(found + 2,lineLength));
    }
}

来自 ReadAllLines 的文档:

This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.

ReadAllLines 已经很好地为您删除了所有换行符,并将每一行作为返回数组中的一个元素。这就是为什么 IndexOf returns -1 - 表示字符串中没有换行符。

要获取行的长度,您不需要查找换行符的位置。只需使用 line.Length:

lineLength = line.Length;

I tried using .length by setting lineLength equal to line.Length but when I put lineLength for the length parameter in line.substring I get an error saying "index and length must refer to a location in the string"?

那是因为那不是 Substring 的工作方式。 Substring的第二个参数是你要的子串的长度,不是结束索引

在这种情况下,如果你想从 found + 2 一直到最后,你可以调用 Substring 的 one-argument 重载:

line.Substring(found + 2)

This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netcore-3.1

System.IO.File.ReadAllLines 函数删除回车 returns 或换行。