2012-12-13 59 views
3

可能重複:
How would you count occurences of a string within a string (C#)?如何計算輸入字符串?

我有一個具有多個子串的字符串,並(按Enter鍵特殊字符)它們之間的輸入。

你能指導我如何編寫一個正則表達式來計算單詞之間的Enter鍵嗎?

謝謝

+4

爲什麼你需要在一個字符串計數的字符出現的次數_regular表情的?這太過分了。只需要以其他方式對角色進行計數。遍歷字符。或者也許有一個庫函數。 –

+0

「Enter」是「\ r \ n」'('CRLF'),''\ n「'('LF')還是'」\ r「'('CR')? –

+3

「嗨,我有一個與字符串有關的問題,我必須要一個正則表達式。」 – ean5533

回答

7

根據在使用的換行符號上,您可能必須更改爲\r\n

var numberLineBreaks = Regex.Matches(input, @"\r\n").Count; 
3

是否必須是正則表達式?可能有更簡單的方法......例如,你可以使用string[] array = String.Split('\n');創建子字符串數組,然後得到與array.Length;

+1

你可能需要從中減去一個結果。 –

+0

這將是非常低效和浪費,因爲OP只需要一個計數。 –

0

計數您可以通過簡單地計算新行做:

int start = -1; 
int count = 0; 
while ((start = text.IndexOf(Environment.NewLine, start + 1)) != -1) 
    count++; 
return count; 
6

你不需要一個正則表達式,你只需要計算字符串。具體來說,你只是計數Environment.Newline s。有很多方法可以做到這一點;在this SO answer中描述了幾種。這裏有一個看起來效率不高,但執行得非常好:

int count1 = source.Length - source.Replace(Environment.Newline, "").Length; 
0

您可以使用此代碼,

using System; 
using System.Text.RegularExpressions; 

class Program 
    { 
     static void Main() 
     { 
     long a = CountLinesInString("This is an\r\nawesome website."); 
     Console.WriteLine(a); 

     long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah."); 
     Console.WriteLine(b); 
     } 

     static long CountLinesInString(string s) 
     { 
      long count = 1; 
      int start = 0; 
      while ((start = s.IndexOf('\n', start)) != -1) 
      { 
       count++; 
       start++; 
      } 
      return count; 
     } 

     static long CountLinesInStringSlow(string s) 
     { 
      Regex r = new Regex("\n", RegexOptions.Multiline); 
      MatchCollection mc = r.Matches(s); 
      return mc.Count + 1; 
     } 
} 
相關問題