4

可能重复:
如何计算字符串中字符串的出现次数(C#)?

我有一个字符串,其中包含多个子字符串和 Enter(按 Enter 键的特殊字符)。

你能指导我如何编写一个计算单词之间输入键的正则表达式吗?

谢谢

4

5 回答 5

9

根据使用的换行符,您可能必须更改为 just\r或 just \n

var numberLineBreaks = Regex.Matches(input, @"\r\n").Count;
于 2012-12-13T03:28:59.983 回答
7

您不需要正则表达式,您只是在计算字符串。具体来说,您只是在数Environment.Newlines。有很多方法可以做到这一点;这个 SO answer中描述了几个。这是一个看起来效率低下但性能出奇的好:

int count1 = source.Length - source.Replace(Environment.Newline, "").Length;
于 2012-12-13T03:32:21.777 回答
3

它必须是正则表达式吗?可能有更简单的方法......例如,您可以使用string[] array = String.Split('\n');创建子字符串数组,然后使用array.Length;

于 2012-12-13T03:26:45.410 回答
0

您可以通过简单地计算换行符来做到:

int start = -1;
int count = 0;
while ((start = text.IndexOf(Environment.NewLine, start + 1)) != -1)
    count++;
return count;
于 2012-12-13T03:28:15.203 回答
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;
         }
 }
于 2012-12-13T03:44:17.693 回答