如何检测连续两个输入字符?

时间:2017-07-24 15:02:31

标签: c# winforms

我试图制作一个Reddit Formatter工具,只要你有一个只有一个换行符的文本来添加另一个换行符并创建一个新的段落。在StackOverflow中它是相同的,你必须按两次回车键才能开始一个新的段落。它来自:

 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");
             }
         }
    }

这太棒了,但如果它已经是双倍的话,我不想添加多个输入字符。我不想从

出发
 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[i - 1] != '\u000A')//if finds a SINGLE new line
             {
                    textBox1.Text = textBox1.Text.Insert(i, "\r\n\r\n");
             }
         }
   }

但它不起作用?它基本相同,但也检查前一个是否也是输入字符

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

提前谢谢

1 个答案:

答案 0 :(得分:0)

让我们将问题分解为两部分

第1部分What am I doing wrong

您的代码会检查连续2个\n字符

if (textBox1.Text[i] == '\u000A' && textBox1.Text[i - 1] != '\u000A')

但是当您在\r找到[i-1]时,您总是会在\n找到[i]个字符。简而言之,您的检查仅用于检测单个\n但从不超过1个连续EOLN

第2部分Best way to do this

RegularExpressions是处理此类事情的最佳方式。它不仅使解析部分易于读/写(如果你知道正则表达式),而且在模式改变时保持灵活性(再次,如果你知道正则表达式)

以下行应该做你需要的

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

的一个实例
相关问题