2017-02-10 23 views
-1

假設我有一個字符串,如下所示:如何在首次換行後取出所有單詞?

User. 
This is first line after line break. 
This is second line after line break. 
//Blank Line 
This is fourth line. 

我如何可以獲取的第一行突破之後出現的所有單詞。 因此,在上述情況下,我想檢索:

該「用戶」的下一行後發生
This is first line after line break. 
This is second line after line break. 
//Blank Line 
This is fourth line. 

即任何東西。

所以基本上字符串將包含以下內容:

User\r\n\r\nThis is first line after line break. //and so on 

我目前做如下:

  // consider demoString is the string variable which holds the entire string mentioned above 

commentStringToSearch = "User"; 
commentStringIndex = demoString.IndexOf(commentStringToSearch, StringComparison.OrdinalIgnoreCase);     

if (commentStringIndex != -1) 
{ 
      commentValue = demoString.Substring(commentStringIndex + commentStringToSearch.Length);   
} 

但這段代碼的問題是,它會後取什麼單詞'User'包括第一行的空格。

我的預期輸出是讓他們從第二行到最後一行中的任何一個。

按照上面的例子我的預期成果是得到如下:

This is first line after line break. 
This is second line after line break. 
//Blank Line 
This is fourth line. 

(忽略一切從第一行,並接受第二行開始的任何東西)

在此先感謝。

+1

拆分。現在你有所有的線路。根據需要繼續。 – Will

+0

獲得「用戶」索引後,只需找到索引後的第一個換行符的索引即可。 – juharr

+0

@stuartd你應該把它作爲答案。 – Fildor

回答

2

有這樣做的一個簡單的方法:

var newText = text.Substring(text.IndexOf(Environment.NewLine) + Environment.NewLine.Length); 
+0

我只想爲OP添加內容:當然,您必須事先檢查您的輸入:Not null,不爲空,至少包含一個換行符... – Fildor

0

@ stuartd的回答解決了我的問題,稍加修改如下:

var newText = text.Substring(text.IndexOf(Environment.NewLine) + Environment.NewLine.Length +2); 

之所以加入2是因爲@ stuartd的解決方案字符串變量將包含以下值:

\r\nThis is first line after line break. //and so on 

由於有一個不想要的\ r \ n正在從原始字符串繼承,有必要添加2以使子字符串跳過它們,否則會有一個不必要的空格被添加到sting值的開始處。

而作爲@Fildor正確地指出,這是必要的,以驗證前手串爲空值等對Environment.NewLine

相關問題