我有以下的代碼,我用它來獲得一個字符串並將由換行符打破它:如何通過換行符分割字符串並且不會在一行中丟失多個換行符?
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
,我不想(因爲它有更多的空間比的條目,我想)
對於初學者,您需要3個換行符才能顯示文本。 – joko
不要刪除空的條目並適當地處理它們。 –
你應該更好地依靠'Environment.NewLine'。關於你想要的,它不能立即用'Split'來完成,它只能提供兩種可能的行爲:忽略所有的break行或者說明所有行(你可以通過'StringSplitOptions'來決定)。另一方面,目標行爲似乎很容易通過循環來補充「Split」。 – varocarbas