2017-07-24 65 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

只是一個實例替換它
相關問題