#方法一:使用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. RHEL/Centos7 安装图形化桌面(转)

    RHEL/Centos7 安装图形化桌面   Linux是一个多任务的多用户的操作系统,好多linux爱好者在安装完linux后经常遇到一个问题——没有图形化桌面.今天小编在安装RHEL7的时候,一步 ...

  2. powerdesigner生成mysql带注释的ER图

    1.安装PowerDesigner的 参考 https://blog.csdn.net/sinat_34104446/article/details/79885141 2配置逆向工程 2.1新建模型p ...

  3. 爬虫之Requests&beautifulsoup

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引.模拟程序或者蠕 ...

  4. kernel笔记——中断

    cpu与磁盘.网卡.键盘等外围设备(相对于cpu和内存而言)交互时,cpu下发I/O请求到这些设备后,相对cpu的处理能力而言,磁盘.网卡等设备需要较长时间完成请求处理. 那么在请求发出到处理完成这段 ...

  5. loadrunner关联及web_reg_save_param方法浅析

    一.什么是关联 关联(correlation):脚本回放过程中,客户端发出请求,通过关联函数所定义的左右边界值(也就是关联规则),在服务器所响应的内容中查找,得到相应的值,已变量的形式替换录制时的静态 ...

  6. 【转】Android辅助功能AccessibilityService自动全选择文字粘贴模拟输入

    网上找了很久AccessibilityService全选文字的方法,一直没找到,自己研究了半天,分享出来. /** * 输入文本 */ public void inputText(List<St ...

  7. Windows服务器环境下jenkins下载和安装

    1.下载jenkins 在windows系统上搭建jenkins持续集成有两种方法:1.war文件,可以用tomcat或者java命令直接运行2.msi安装,作为系统服务后台运行 下载地址 https ...

  8. C++ shared_ptr、unique_ptr、weak_ptr

    shared_ptr unique_ptr weak_ptr 内存泄漏 智能指针 引用计数 循环引用 reset

  9. 使用Flame Graph进行系统性能分析

    关键词:Flame Graph.perf.perl. FlameGraph是由BrendanGregg开发的一款开源可视化性能分析工具,形象的成为火焰图. 从底向上像火苗一样逐渐变小,也反映了相互之间 ...

  10. centos7内网源站建设

    centos7内网源站建设 1.部署环境: 系统:Centos7 x86_64 应用服务:nginx.createrepo.reposync 镜像源:https://mirrors.aliyun.co ...