首页 > 代码库 > C#中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?

C#中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?

C#中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?这是一个很常见的命题,以前也没有注意,今天QQ群里有人提起,于是就做了下试验,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Diagnostics;
 
namespace ConsoleApplication1
{
    class Program
    {
        private const int N = 10000000;
        private static Stopwatch watch = new Stopwatch();
        static void Main(string[] args)
        {
 
            string source = "abcdefghijklmnopqrstuvwxyz0123456789C#"
                          + "中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?.uonun";
            string target = "a";
            Console.WriteLine("目标为第一个字符时:");
            TestContains(source, target);
            TestIndexOf(source, target);
            Console.WriteLine();
 
            Console.WriteLine("目标为中部某个字符时:");
            target = "中";
            TestContains(source, target);
            TestIndexOf(source, target);
            Console.WriteLine();
 
            Console.WriteLine("目标为最后一个字符时:");
            target = "u";
            TestContains(source, target);
            TestIndexOf(source, target);
 
            Console.WriteLine("执行完毕,按任意键退出...");
            Console.ReadKey();
 
        }
        private static void TestIndexOf(string source, string target)
        {
            watch.Reset();
            watch.Start();
            for (int i = 0;i < N;i++)
            {
                source.IndexOf(target);
            }
            watch.Stop();
            Console.WriteLine("IndexOf: " + watch.ElapsedMilliseconds.ToString() + "ms");
            return;
        }
 
        private static void TestContains(string source, string target)
        {
            watch.Reset();
            watch.Start();
            for (int i = 0;i < N;i++)
            {
                source.Contains(target);
            }
            watch.Stop();
            Console.WriteLine("Contains: " + watch.ElapsedMilliseconds.ToString() + "ms");
            return;
        }
    }
}

 

得到的结果是:

目标为第一个字符时:
Contains: 973ms
IndexOf: 1343ms

目标为中部某个字符时:
Contains: 1813ms
IndexOf: 8602ms

目标为最后一个字符时:
Contains: 1433ms
IndexOf: 5094ms
执行完毕,按任意键退出...

 

可以看出,使用Contains方法的效率比IndexOf的效率高很多。