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

  

 #方法一:使用string.Contains方法

  string.Contains是大小寫敏感的,若是要用該方法來判斷一個string是否包含某個關鍵字keyword,須要把這個string和這個keyword都轉成小寫或大寫再調用Contains方法;api

1 string key = "bbb";
2 string temp = "aaaBBBcccDDD";
3 bool isContains= temp.ToLower().Contains(key.ToLower());//true

#方法二:使用sring.IndexOf方法

  使用string.Index方法,而後經過StringComparison.OrdinalIgnoreCase指定查找過程忽略大小寫;oop

1 string key = "bbb";
2 string temp = "aaaBBBcccDDD";
3 bool isContains = temp.IndexOf(key,StringComparison.OrdinalIgnoreCase)>=0;//true

 #當設計到大小寫的問題時,那何時使用Contains的上述方法,何時使用IndexOf的上述方法,哪一個效率高?

  contains方法的源碼中實際上是使用了IndexOf方法的,但效率仍是有差異的;測試

一、測試代碼:基於.net4.5

  注:此測試針對的是擁有大量英文的狀況下,而且指定的字符串爲英文this

  每一個方法測試1千萬次,輸出所用時間;spa

 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     }

二、測試結果:

三、總結

  一、從測試結果(大量測試)中能明顯看出,當擁有大量英文的字符串中:.net

  *當不區分大小寫時,string.IndexOf方法的效率明顯高於string.Contains方法;pwa

  *當區分大小寫時,string.Contains方法的效率明顯高於string.IndexOf方法;設計

  *若是判斷的是中文,沒有大小寫之分,仍是string.Contains方法的效率高;code

  二、綜合上述總結,定義了一個String擴展方法,該方法包含一個StringComparison參數,返回值爲是否包含子字符串:blog

    參考:https://docs.microsoft.com/zh-cn/dotnet/api/system.string.contains?redirectedfrom=MSDN&view=netframework-4.5#System_String_Contains_System_String_

 1 using System;
 2 
 3 public static class StringExtensions
 4 {
 5    public static bool Contains(this String str, String substring, 
 6                                StringComparison comp)
 7    {                            
 8       if (substring == null)
 9          throw new ArgumentNullException("substring", 
10                                          "substring cannot be null.");
11       else if (! Enum.IsDefined(typeof(StringComparison), comp))
12          throw new ArgumentException("comp is not a member of StringComparison",
13                                      "comp");
14 
15       return str.IndexOf(substring, comp) >= 0;                      
16    }
17 }
 1 using System;
 2 
 3 public class Example
 4 {
 5    public static void Main()
 6    {
 7       String s = "This is a string.";
 8       String sub1 = "this";
 9       Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1);
10       StringComparison comp = StringComparison.Ordinal;
11       Console.WriteLine("   {0:G}: {1}", comp, s.Contains(sub1, comp));
12       
13       comp = StringComparison.OrdinalIgnoreCase;
14       Console.WriteLine("   {0:G}: {1}", comp, s.Contains(sub1, comp));
15    }
16 }
17 // The example displays the following output:
18 //       Does 'This is a string.' contain 'this'?
19 //          Ordinal: False
20 //          OrdinalIgnoreCase: True
相關文章
相關標籤/搜索