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