C# 如何检测一行中的两个enter字符?

C# 如何检测一行中的两个enter字符?,c#,winforms,C#,Winforms,我正在尝试制作一个Reddit格式工具,每当你有一个只有一个换行符的文本时,就可以添加另一个换行符并生成一个新段落。在StackOverflow中也是一样,您必须按两次enter键才能开始新的段落。它将从: Roses are red Violets are Blue Roses are red Violets are Blue 到 下面的代码起作用:它通过检查文本框中输入的文本中的每个字符(从末尾开始)来检测输入字符,并在单击按钮后将其替换为双字符 private voi

我正在尝试制作一个Reddit格式工具,每当你有一个只有一个换行符的文本时,就可以添加另一个换行符并生成一个新段落。在StackOverflow中也是一样,您必须按两次enter键才能开始新的段落。它将从:

 Roses are red
 Violets are Blue
 Roses are red

 Violets are Blue

下面的代码起作用:它通过检查文本框中输入的文本中的每个字符(从末尾开始)来检测输入字符,并在单击按钮后将其替换为双字符

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = textBox1.Text.Length - 1; i >= 0; i--)
        {
             if (textBox1.Text[i] == '\u000A')
             {
                    textBox1.Text = textBox1.Text.Insert(i, "\r\n\r\n");
             }
         }
    }
这很好,但是如果它已经是双精度的,我不想添加多个enter字符。我不想离开

因为它已经作为第一个例子起作用了。如果你一直按这个按钮,它只会无限地增加更多的行

我试过这个:

    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = textBox1.Text.Length - 1; i >= 0; i--) 
        {

             if (textBox1.Text[i] == '\u000A' && textBox1.Text[i - 1] != '\u000A')//if finds a SINGLE new line
             {
                    textBox1.Text = textBox1.Text.Insert(i, "\r\n\r\n");
             }
         }
   }
但它不起作用?它基本上是相同的,但也检查前一个字符是否也是enter字符

我做错了什么?我真的很困惑,因为它应该有效。。。输出与第一个代码完全相同


提前谢谢

让我们把问题分成两部分

第1部分
我做错了什么

您的代码检查是否有2个连续的
\n
字符

if (textBox1.Text[i] == '\u000A' && textBox1.Text[i - 1] != '\u000A')
但是当您在
[i]
中找到
\n
时,您总是在
[i-1]
中找到
\r
字符。简言之,您的检查仅用于检测单个
\n
,但不会超过1个连续的EOLN

第2部分
实现这一点的最佳方法

是处理这些事情的最好方法。它不仅使解析部分易于读/写(如果您知道regex),而且在模式更改时保持灵活性(如果您知道regex,同样如此)

下面这行应该是你需要的

textBox1.Text = Regex.Replace(textBox1.Text, "(?:\r\n)+", "\r\n\r\n");
让我给你解释一下正则表达式

(?:xxx)        This is just a regular bracket (ignore the xxx, as that is just a placeholder) to group together things without capturing them
+              The plus sign after the bracket tells the engine to capture one or more instances of the item preceding it which in this case is `(?:\r\n)`

因此,正如您可能已经意识到的,我们正在寻找一个或多个
\r\n
实例,并将其替换为
\r\n

的一个实例,首先更改
int i=textBox1.Text.Length-1;i>=0;i--
to
int i=textBox1.Text.Length-1;i>0;我--
否则它将抛出异常。好的,非常感谢,现在已修复
textBox1.Text = Regex.Replace(textBox1.Text, "(?:\r\n)+", "\r\n\r\n");
(?:xxx)        This is just a regular bracket (ignore the xxx, as that is just a placeholder) to group together things without capturing them
+              The plus sign after the bracket tells the engine to capture one or more instances of the item preceding it which in this case is `(?:\r\n)`