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


C#中查詢字符串中是否包含指定字符/串,使用IndexOf還是Contains?這是一個很常見的命題,以前也沒有注意,今天QQ群里有人提起,於是就做了下試驗,代碼如下:

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的效率高很多。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM