2011-04-22 89 views
0

例如,計算新線的出現次數?

string="help/nsomething/ncrayons" 

輸出:

String word count is: 3 

這是我有什麼,但在程序循環,雖然該方法幾次,它看起來像我只得到最後創建的字符串。這裏的代碼塊:

Regex regx = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase); 
MatchCollection matches = regx.Matches(output); 
//int counte = 0; 
foreach (Match match in matches) 
{ 
    //counte = counte + 1; 
    links = links + match.Value + '\n'; 
    if (links != null) 
    { 
     string myString = links; 
     string[] words = Regex.Split(myString, @"\n"); 

     word_count.Text = words.Length.ToString(); 
    } 

} 

它是\n換行。

+0

。我們可以假設你的意思是\ n對於換行符,但如果你能清楚這一點會更好嗎? – rtpHarry 2011-04-22 22:15:07

回答

2

不知道正則表達式是你的情況必須的,但你可以使用split

string myString = "help/nsomething/ncrayons"; 
string[] separator = new string[] { "/n" }; 
string[] result = myString.Split(separator, StringSplitOptions.None); 
MessageBox.Show(result.Count().ToString()); 

使用正則表達式的另一種方式:與/ n的整個問題,你是混合\ n

string myString = "help/nsomething/ncrayons"; 
string[] words = Regex.Split(myString, @"/n"); 
word_count.Text = words.Length; 
+0

當我嘗試使用「Count」時,出現以下錯誤:Error 'System.Array'不包含'Count'的定義,也沒有擴展方法'Count'接受類型的第一個參數'System.Array'可以找到(你是否缺少使用指令或程序集引用?) – Jason 2011-04-22 21:22:12

+0

@Jason它適用於我在VS 2010,.net 3.5和4.0上的罰款你的目標是什麼框架? – Prix 2011-04-22 21:25:43

+0

我正在使用4.0。我使用這個代碼,它不喜歡它:word_count.Text = result.Count()。ToString(); – Jason 2011-04-22 21:26:47