2017-07-24 69 views
0

我试图做一个Reddit格式工具,只要你有一个文本只有一个换行符就可以添加另一个文件并创建一个新段落。这里在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"); 
      } 
     } 
    } 

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

我在做什么错?我真的很困惑,因为它应该工作...输出是

预先感谢您完全一样,第一个代码

+0

首先改变'int i = textBox1.Text.Length - 1; i> = 0;我 - '到'诠释我= textBox1.Text.Length - 1; i> 0;我 - “否则它会抛出异常。 – KamikyIT

+0

好的,非常感谢,现在修好了 – Gloow8

回答

0

让我们来分析这个问题分解成两个部分

部分#1What am I doing wrong

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

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

但是当您发现\n[i]时,您总是最终找到\r字符[i-1]。总之你的支票只能检测单个\n但从未连续超过1个EOLNs

部分#2Best 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

只是一个实例替换它
相关问题