【问题标题】:How to detect two enter characters in a row?如何检测连续输入的两个字符?
【发布时间】:2017-07-24 15:02:31
【问题描述】:

我正在尝试制作一个 Reddit Formatter 工具,每当您有一个只有一个换行符的文本来添加另一个并创建一个新段落时。在 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");
             }
         }
    }

这很好,但如果它已经是一个双精度字符,我不想添加多个输入字符。我不想离开

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

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

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

提前谢谢你

【问题讨论】:

  • 首先将int i = textBox1.Text.Length - 1; i >= 0; i--改为int i = textBox1.Text.Length - 1; i > 0; i--,否则会抛出异常。
  • 好的,非常感谢,现在修好了

标签: c# winforms


【解决方案1】:

让我们把问题分成两部分

第 1 部分What am I doing wrong

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

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

但是当你在[i] 找到\n 时,你总是在[i-1] 找到\r 字符。简而言之,您的检查只能检测单个 \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 实例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多