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

  string.Contains是大小写敏感的,如果要用该方法来判断一个string是否包含某个关键字keyword,需要把这个string和这个keyword都转成小写或大写再调用Contains方法;

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

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

  使用string.Index方法,然后通过StringComparison.OrdinalIgnoreCase指定查找过程忽略大小写;

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

#当设计到大小写的问题时,那什么时候使用Contains的上述方法,什么时候使用IndexOf的上述方法,哪个效率高?

  contains方法的源码中其实是使用了IndexOf方法的,但效率还是有差别的;

1、测试代码:基于.net4.5

  注:此测试针对的是拥有大量英文的情况下,并且指定的字符串为英文

  每个方法测试1千万次,输出所用时间;

 class Program
{
private const int N = ;
private static Stopwatch watch = new Stopwatch();
static void Main(string[] args)
{ string source = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqq";
string target = "AAA";
Console.WriteLine("目标在开头部分时:");
Console.WriteLine("不区分大小写:");
TestContains(source, target,true);
TestIndexOf(source, target,true);
Console.WriteLine("区分大小写:");
target = "aaa";
TestContains(source, target,false);
TestIndexOf(source, target,false);
Console.WriteLine(); Console.WriteLine("目标在中部时:");
Console.WriteLine("不区分大小写:");
target = "HHH";
TestContains(source, target, true);
TestIndexOf(source, target, true);
Console.WriteLine("区分大小写:");
target = "hhh";
TestContains(source, target, false);
TestIndexOf(source, target, false);
Console.WriteLine(); Console.WriteLine("目标在结尾时:");
Console.WriteLine("不区分大小写:");
target = "QQQ";
TestContains(source, target,true);
TestIndexOf(source, target,true);
Console.WriteLine("区分大小写:");
target = "qqq";
TestContains(source, target,false);
TestIndexOf(source, target,false); Console.WriteLine("执行完毕,按任意键退出...");
Console.ReadKey(); }
private static void TestIndexOf(string source, string target,bool isIgnoreCase)
{
watch.Reset();
watch.Start();
for (int i = ; i < N; i++)
{
if (isIgnoreCase)
source.IndexOf(target, StringComparison.OrdinalIgnoreCase);
else
source.IndexOf(target);
}
watch.Stop();
Console.WriteLine("IndexOf: " + watch.ElapsedMilliseconds.ToString() + "ms");
return;
} private static void TestContains(string source, string target,bool isIgnoreCase)
{
watch.Reset();
watch.Start();
for (int i = ; i < N; i++)
{
if (isIgnoreCase)
source.ToLower().Contains(target.ToLower());
else
source.Contains(target);
}
watch.Stop();
Console.WriteLine("Contains: " + watch.ElapsedMilliseconds.ToString() + "ms");
return;
}
}

2、测试结果:

3、总结

  1、从测试结果(大量测试)中能明显看出,当拥有大量英文的字符串中:

  *当不区分大小写时,string.IndexOf方法的效率明显高于string.Contains方法;

  *当区分大小写时,string.Contains方法的效率明显高于string.IndexOf方法;

  *如果判断的是中文,没有大小写之分,还是string.Contains方法的效率高;

  2、综合上述总结,定义了一个String扩展方法,该方法包含一个StringComparison参数,返回值为是否包含子字符串:

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

 using System;

 public static class StringExtensions
{
public static bool Contains(this String str, String substring,
StringComparison comp)
{
if (substring == null)
throw new ArgumentNullException("substring",
"substring cannot be null.");
else if (! Enum.IsDefined(typeof(StringComparison), comp))
throw new ArgumentException("comp is not a member of StringComparison",
"comp"); return str.IndexOf(substring, comp) >= ;
}
}
 using System;

 public class Example
{
public static void Main()
{
String s = "This is a string.";
String sub1 = "this";
Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1);
StringComparison comp = StringComparison.Ordinal;
Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); comp = StringComparison.OrdinalIgnoreCase;
Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp));
}
}
// The example displays the following output:
// Does 'This is a string.' contain 'this'?
// Ordinal: False
// OrdinalIgnoreCase: True

  

【C#】判断字符串中是否包含指定字符串,contains与indexof方法效率问题的更多相关文章

  1. PHP判断字符串中是否包含指定字符串,支持中文哦

    RT,随手写的 /** * 判断字符串中是否包含指定字符串 * @var source 源字符串 * @var target 要判断的是否包含的字符串 * @return bool */ functi ...

  2. Node.js之判断字符串中是否包含某个字符串

    server.txt内容如下: 阿里云服务器 关于应用场景,就不多说了,字符串是不论是后端开发还是前端开发等,都是要经常打交道了. test.js(node.js代码,只要被本地装了node.js环境 ...

  3. ***用php的strpos() 函数判断字符串中是否包含某字符串的方法

    判断某字符串中是否包含某字符串的方法 if(strpos('www.idc-gz.com','idc-gz') !== false){ echo '包含'; }else{ echo '不包含'; } ...

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

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

  5. sql判断以逗号分隔的字符串中是否包含某个字符串--------MYSQL中利用select查询某字段中包含以逗号分隔的字符串的记录方法

    sql判断以逗号分隔的字符串中是否包含某个字符串---------------https://blog.csdn.net/wttykj/article/details/78520933 MYSQL中利 ...

  6. python判断字符串中是否包含子字符串

    python判断字符串中是否包含子字符串 s = '1234问沃尔沃434' if s.find('沃尔沃') != -1:     print('存在') else:     print('不存在' ...

  7. ---iOS开发 截取字符串中两个指定字符串中间的字符串---

    例如,要截取一个字符串中,两个指定字符串中间的字符串,OC截取方法如下: // 要截取 "> 和 </ 之间的汉字内容: @implementationViewControlle ...

  8. MySQL:判断逗号分隔的字符串中是否包含某个字符串 && 如何在一个以逗号分隔的列表中的一个字段中连接MySQL中的多对多关系中的数据

    需求:      sql语句中,判断以逗号分隔的字符串中是否包含某个特定字符串,类似于判断一个数组中是否包含某一个元素, 例如:判断 'a,b,c,d,e,f,g' 中是否包含 'a',sql语句如何 ...

  9. 判断字符串中是否包含指定的内容&&字符串截取方法比较说明

    1.使用indexOf()方法 方法说明: 作用:indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置(从前向后查找). 语法:stringObject.indexOf(searc ...

随机推荐

  1. C#中FormsAuthentication用法实例

    ....本文纯属抄袭....   using System; using System.Web; using System.Web.Security;   namespace AuthTest {   ...

  2. Sql Server 获取本周周一

    SELECT DATEADD(Day,(@i+1)-(DATEPART(Weekday,getdate())+@@DATEFIRST-1)%7,getdate())

  3. Boosting Static Representation Robustness for Binary Clone Search against Code Obfuscation and Compiler Optimization(二)

    接着上篇Asm2Vec神经网络模型流程继续,接下来探讨具体过程和细节. 一.为汇编函数建模  二.训练,评估   先来看第一部分为汇编函数建模,这个过程是将存储库中的每一个汇编函数建模为多个序列.由于 ...

  4. PuTTY 串口调试,为普通用户增加访问串口设备权限

    一般情况下,只有 root 用户可以使用 PuTTY 访问串口设备,如果要为普通用户增加访问串口设备的权限,可按如下步骤进行: (以 Ubuntu 14.04.3 系统为例,第一个串口设备,会被识别为 ...

  5. js获取浏览器窗体最大化事件

    <mce:script language="javascript"><!--function ReSet() {document.getElementById(& ...

  6. 《通过C#学Proto.Actor模型》之Supervision

    Supervision,字面意思是监督,是父Actor发现子Actor有异常发生后,对子Actor产用保种策略处理的机制,如果父Actor不处理,则往上传递. 子Actor发生异常后处理的策略有: R ...

  7. MongoDB Change Stream:简介、尝试与应用

    在MongoDB3.6引入的新feature中,change stream无疑是非常吸引人的. Change streams allow applications to access real-tim ...

  8. 三:OVS+GRE之完整网络流程

    知识点一:linux网桥提供安全组 知识点二:每新建一个网络,在网络节点都会新建一个namespace,只要为该网络建立子网,那么该namespace里就新增dhcp来为该子网分配ip,也可以为该网络 ...

  9. iOS开发基础-UIScrollView基础

     普通的 UIView 不具备滚动功能,不能显示过多的内容.UIScrollView 是一个能够滚动的视图控件,可用来展示大量的内容.  UIScrollView 的简单使用: 1)将需要展示的内容添 ...

  10. Auto Layout - BNR

    继续UIImageView - BNR篇. 通过Homepwner TARGETS -> General -> Deployment Info -> Devices中的iPhone改 ...