2012-07-10 106 views
2

首先:對不起我的英文不好!閱讀字符串像StreamReader

我知道標題是不是最好的英語,但我真的不知道如何格式化這個問題...
我試圖做的是逐行讀取的HTML源代碼行,以便當看到一個給定的單詞(如http://)它會複製整個句子,因此我可以刪除剩下的只保留該URL。

這是我已經試過:

using (var source = new StreamReader(TempFile)) 
{ 
    string line; 
    while ((line = source.ReadLine()) != null) 
    { 
     if (line.Contains("http://")) 
     { 
      Console.WriteLine(line); 
     } 
    } 
} 

這工作完全,如果我想從外部文件中讀取,但是當我想讀一個字符串或StringBuilder的,怎麼辦這是行不通的你逐行閱讀這些內容?

回答

6

您可以使用new StringReader(theString)做了string,但我懷疑你的整體戰略。用HTML敏捷包這樣的工具會更好。

例如,這裏是HTML敏捷性包提取的所有超鏈接:

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(theString); 
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href]") 
{ 
    HtmlAttribute att = link["href"]; 
    Console.WriteLine(att.Value); 
} 
+1

我同意。另外請確保使用ScrapySharp以及HtmlAgilityPack。讓你用熟悉的jQuery語法來選擇元素。從字面上提高你的生產力。 http://www.romcyber.com/post/2012/01/27/ScrapySharp-in-english-%29.aspx – 2012-07-10 22:30:31

+0

@SergioTapia酷;我沒有聽說過那個;將嘗試 – 2012-07-10 22:32:57

+0

但這是另一個依賴項......並不是說它一定是壞的,只是一個需要考慮的事情。 – vines 2012-07-10 22:35:32

0

那麼一個字符串只是一個字符串,它沒有任何行。

您可以使用類似String.Split的東西來分開\r符號。

MSDN:String.Split()

string words = "This is a list of words, with: a bit of punctuation" + 
         "\rand a newline character."; 

string [] split = words.Split(new Char [] {'\r' }); 

foreach (string s in split) { 
    if (s.Trim() != "")  
     Console.WriteLine(s); 
} 
0

描述我想你可以標記化的輸入並檢查所要求的內容的每個條目。

string[] info = myStringBuilder.toString().split[' ']; 
foreach(var item in info) { 
if(item.Contains('http://') { 
    //work with it 
    } 
} 
0

您可以使用內存流來讀取。