日期:2014-05-18  浏览次数:20870 次

高人,来个算法.进来瞧瞧
程序需求如下:
判断一个文本文件中,某一字符串存在的个数.(文本文件体积,超过10M)
比如判断文本文件a.txt中,字符串"ul"在此文本文件中的个数.我写了下面两个算法.
  private static void A1(string str, string str1)
  {
  DateTime d1 = DateTime.Now;
  int pos = 0;
  int total = -1;
  while (pos != -1)
  {
  pos = str.IndexOf(str1, pos+1);
  total++;
  }
  TimeSpan t = DateTime.Now - d1;
  System.Console.WriteLine("共有{0}个匹配字符串,耗时{1}毫秒", total, t.TotalMilliseconds);


  }
  private static void A3(string str, string str1)
  {
  DateTime d1 = DateTime.Now;
  int total = 0;
  System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(str, str1);
  total = mc.Count;
  TimeSpan t = DateTime.Now - d1;
  System.Console.WriteLine("共有{0}个匹配字符串,耗时{1}毫秒", total, t.TotalMilliseconds);
  }

第二个算法,在性能上,要优于第一个算法,可是,还不太理想,有没有更快的算法?如果有,请附上源代码.

------解决方案--------------------
把文件一次读到一个string中吗?载入文件分配内存也是很耗时间的
计算时间要把载入的部分也计算上先
------解决方案--------------------
对方法2的改进:
Regex regex = new Regex(regexstr, RegexOptions.Compiled);
mc = regex.Match(inputstr);
如果要做的数据量很大,或者是一个正则被重复的使用则可以采用编译型的正则

另外关于楼主时间的采样方法是不精确的。OS是多任务的,关于你代码的运行时间应该取
TimeSpan beginTime = System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime;
//这里跑算法
TimeSpan endTime = System.Diagnostics.Process.GetCurrentProcess().TotalProcessorTime;
TimeSpan totalTime = endTime.Subtract(beginTime);
如果程序运行的时间很短是误差很大的
------解决方案--------------------
C# code

楼主可以先将文本文件读入一个字符串中,然后
判断一个字符串在另外一个字符串中的个数的方法很多:
1、string str1='ul';
   string str2='ulasdulauldsduls';
   string[] st=s.Split(str1.ToCharArray()); 
   int n=st.Length-1; //

2.string str1='ul';
  string str2='ulasdulauldsduls';
  int n=str2.length-str2.Replace(str1,'').length;

等等还有很多。。