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 ;
}
}
}
|