1. 程式人生 > >【C#】判斷字串中是否包含指定字串,contains與indexof方法效率問題

【C#】判斷字串中是否包含指定字串,contains與indexof方法效率問題

 1 class Program
 2     {
 3         private const int N = 10000000;
 4         private static Stopwatch watch = new Stopwatch();
 5         static void Main(string[] args)
 6         {
 7 
 8             string source = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqq";
 9             string target = "
AAA"; 10 Console.WriteLine("目標在開頭部分時:"); 11 Console.WriteLine("不區分大小寫:"); 12 TestContains(source, target,true); 13 TestIndexOf(source, target,true); 14 Console.WriteLine("區分大小寫:"); 15 target = "aaa"; 16 TestContains(source, target,false
); 17 TestIndexOf(source, target,false); 18 Console.WriteLine(); 19 20 Console.WriteLine("目標在中部時:"); 21 Console.WriteLine("不區分大小寫:"); 22 target = "HHH"; 23 TestContains(source, target, true); 24 TestIndexOf(source, target, true
); 25 Console.WriteLine("區分大小寫:"); 26 target = "hhh"; 27 TestContains(source, target, false); 28 TestIndexOf(source, target, false); 29 Console.WriteLine(); 30 31 Console.WriteLine("目標在結尾時:"); 32 Console.WriteLine("不區分大小寫:"); 33 target = "QQQ"; 34 TestContains(source, target,true); 35 TestIndexOf(source, target,true); 36 Console.WriteLine("區分大小寫:"); 37 target = "qqq"; 38 TestContains(source, target,false); 39 TestIndexOf(source, target,false); 40 41 Console.WriteLine("執行完畢,按任意鍵退出..."); 42 Console.ReadKey(); 43 44 } 45 private static void TestIndexOf(string source, string target,bool isIgnoreCase) 46 { 47 watch.Reset(); 48 watch.Start(); 49 for (int i = 0; i < N; i++) 50 { 51 if (isIgnoreCase) 52 source.IndexOf(target, StringComparison.OrdinalIgnoreCase); 53 else 54 source.IndexOf(target); 55 } 56 watch.Stop(); 57 Console.WriteLine("IndexOf: " + watch.ElapsedMilliseconds.ToString() + "ms"); 58 return; 59 } 60 61 private static void TestContains(string source, string target,bool isIgnoreCase) 62 { 63 watch.Reset(); 64 watch.Start(); 65 for (int i = 0; i < N; i++) 66 { 67 if (isIgnoreCase) 68 source.ToLower().Contains(target.ToLower()); 69 else 70 source.Contains(target); 71 } 72 watch.Stop(); 73 Console.WriteLine("Contains: " + watch.ElapsedMilliseconds.ToString() + "ms"); 74 return; 75 } 76 }