2015-12-18 89 views
1

我有以下的代碼,我用它來獲得一個字符串並將由換行符打破它:如何通過換行符分割字符串並且不會在一行中丟失多個換行符?

var delimiters = new string[] { "\\v", "\v", "\r", "\n" }; 
string[] split = textWithStyle.Text.Split(
        delimiters, 
        StringSplitOptions.RemoveEmptyEntries); 

我然後依次通過分割陣列來呈現。所以,如果我的字符串是:

Today is Monday and the 7th 
Tomorrow is Tuesday and the 8th 

我得到2項的數組:

[0] Today is Monday and the 7th 
[1] Tomorrow is Tuesday and the 8th 

我剛剛意識到的問題是,如果字符串連續多換行,如:

Today is Monday and the 7th 


Tomorrow is Tuesday and the 8th 

如果我在文本編輯器中查看,我在一行中看到多個CRLF,但我的解析代碼沒有區分這種用例與單個換行符,上面仍然只會創建2個元素與數組他個人行

我該如何更改我的解析代碼,所以如果我在一行中有多個換行符,它會將除第一個換行符外的每一行都添加到數組中。因此,如果上面的字符串有3個CRLFs的話,我想我的數組是:

[0] Today is Monday and the 7th 
[1] empty string 
[2] empty string 
[3] Tomorrow is Tuesday and the 8th 

如果我只是刪除StringSplitOptions.RemoveEmptyEntries,然後我拉閘越來越

[0] Today is Monday and the 7th 
[1] empty string 
[2] empty string 
[3] empty string 
[4] empty string 
[5] Tomorrow is Tuesday and the 8th 

,我不想(因爲它有更多的空間比的條目,我想)

+2

對於初學者,您需要3個換行符才能顯示文本。 – joko

+3

不要刪除空的條目並適當地處理它們。 –

+4

你應該更好地依靠'Environment.NewLine'。關於你想要的,它不能立即用'Split'來完成,它只能提供兩種可能的行爲:忽略所有的break行或者說明所有行(你可以通過'StringSplitOptions'來決定)。另一方面,目標行爲似乎很容易通過循環來補充「Split」。 – varocarbas

回答

1

刪除StringSplitOptions.RemoveEmptyEntries和刪除一些條目,並見好就收:

var delimiters = new string[] { "\\v", "\v", "\r\n" }; 
string[] split = textWithStyle.Text.Split(delimiters); 

對於結果數組中的每個空條目,這是換行符。

+0

如果我這樣做,我會得到5個條目,其中有空字符串。我只想要2 – leora

+0

然後從你的拆分選項中刪除\\ v \ v和\ r,這樣你只能拆分換行符(並且在拆分之前將它們從字符串中刪除) –

+0

我已經更新了我的問題以澄清。我也需要支持段落中斷。另外,你可以舉一個你的評論的例子 – leora

0

首先,我建議使用Environment.NewLine而不是你的構造。通過使用("\\r", "\\n"),您將獲得事件更多的空字符串。

第二次避免StringSplitOptions.RemoveEmptyEntries。要獲得所有換行符,您需要指定StringSplitOptions.None(似乎沒有string[]而沒有StringSplitOptions的超載)。

然後「手動」過濾它。我在這裏看不到一個聰明的linq單線程。

 List<string> resultList = new List<string>(); 
     bool previousEmpty = false; 
     foreach (string split in textWithStyle.Text.Split(new[] {Environment.NewLine, "\v"}, StringSplitOptions.None)) 
     { 
      if (!string.IsNullOrEmpty(split)) 
       previousEmpty = false; 
      else if (!previousEmpty) 
      { 
       previousEmpty = true; 
       continue; 
      }    

      resultList.Add(split); 
     } 

     string[] split = resultList.ToArray(); 

編輯:這對我來說並不完全清楚,如果你想要額外的條目\ r和\ n。您的示例結果表明。如果是這樣,請跳過Environment.NewLine零件並使用分隔器。

但是實際上你會得到你的「不需要」的例子結果,因爲有兩個換行符(\ r \ n \ r \ n => 4個條目)有4個空條目。所以你可能想要更改爲new[]{"\v", "\r\n"}。什麼是"\\v"在你的問題?