C# - 通过逐个字符读取字符串来读取换行符

C# - Reading NewLine characters from reading a string character by character

所以我有一个执行 for 循环的程序,一个一个地读取每个字符,并使用 case 语句将其替换为与该特定字母相关的四位数字。

我的问题是无法读取换行符 ('\n'),我不知道如何解决这个问题。

这是我的代码:

 for (int i = 0; i < inputTextBox.Text.Length; i++)
        {
            //Encryption
            switch (inputTextBox.Text[i])
            {
                // I got rid of the rest of the cases
                // as they are not relevant
                case '\n':
                    encryptedString = encryptedString + "8024";
                    break;
            }
        }

并且由于它不接受新行作为字符,因此不会将其添加到 encryptedString。

这似乎是一个重复的问题,但我发现的其他帖子实际上处于完全不同的情况。

编辑---------------------------------------- ---------------------------------------------- ------------------------------ 所以在调试之后,事实证明它实际上是在读取 '\n' 它只是在解码时没有将它写入字符串。

这里是解码部分的代码:

            for (int i = 0; i < readString.Length; i = i + 4)
            {
            //Decryption
            switch (readString.Substring(i, 4))
            {
                case "8024":
                    decryptedString = decryptedString + "\n";
                    break;
            }
        }
        inputTextBox.Text = decryptedString;

所以它正在到达 "decryptedString = decryptedString + "\n";" line 它只是出于某种原因没有向字符串添加新行。为了确定,我也尝试过使用 '\n' 而不是 "\n"。

首先尝试用这个 Regex.Replace(inputTextBox.Text, "\r\D\n?|\n\D\r?", "\n"); 替换新行
编辑:你确定它没有用吗?
例如,如果加密字符串是:

First string
second
3rd
fourth

使用这个:

encryptedString = Regex.Replace(encryptedString, "\r\D\n?|\n\D\r?", "\n");
encryptedString = encryptedString.Replace("\n", "8024");

将使 encryptedString = First string8024second80243rd8024fourth 是您想要的吗?

我在用 "System.Environment.NewLine" 解码换行符时替换了“\n”,它解决了问题。