【C#】判断字符串中是否包含指定字符串,contains与indexof方法效率问题
#方法一:使用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参数,返回值为是否包含子字符串:
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方法效率问题的更多相关文章
- PHP判断字符串中是否包含指定字符串,支持中文哦
RT,随手写的 /** * 判断字符串中是否包含指定字符串 * @var source 源字符串 * @var target 要判断的是否包含的字符串 * @return bool */ functi ...
- Node.js之判断字符串中是否包含某个字符串
server.txt内容如下: 阿里云服务器 关于应用场景,就不多说了,字符串是不论是后端开发还是前端开发等,都是要经常打交道了. test.js(node.js代码,只要被本地装了node.js环境 ...
- ***用php的strpos() 函数判断字符串中是否包含某字符串的方法
判断某字符串中是否包含某字符串的方法 if(strpos('www.idc-gz.com','idc-gz') !== false){ echo '包含'; }else{ echo '不包含'; } ...
- C#中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?
C#中查询字符串中是否包含指定字符/串,使用IndexOf还是Contains?这是一个很常见的命题,以前也没有注意,今天QQ群里有人提起,于是就做了下试验,代码如下: using System; u ...
- sql判断以逗号分隔的字符串中是否包含某个字符串--------MYSQL中利用select查询某字段中包含以逗号分隔的字符串的记录方法
sql判断以逗号分隔的字符串中是否包含某个字符串---------------https://blog.csdn.net/wttykj/article/details/78520933 MYSQL中利 ...
- python判断字符串中是否包含子字符串
python判断字符串中是否包含子字符串 s = '1234问沃尔沃434' if s.find('沃尔沃') != -1: print('存在') else: print('不存在' ...
- ---iOS开发 截取字符串中两个指定字符串中间的字符串---
例如,要截取一个字符串中,两个指定字符串中间的字符串,OC截取方法如下: // 要截取 "> 和 </ 之间的汉字内容: @implementationViewControlle ...
- MySQL:判断逗号分隔的字符串中是否包含某个字符串 && 如何在一个以逗号分隔的列表中的一个字段中连接MySQL中的多对多关系中的数据
需求: sql语句中,判断以逗号分隔的字符串中是否包含某个特定字符串,类似于判断一个数组中是否包含某一个元素, 例如:判断 'a,b,c,d,e,f,g' 中是否包含 'a',sql语句如何 ...
- 判断字符串中是否包含指定的内容&&字符串截取方法比较说明
1.使用indexOf()方法 方法说明: 作用:indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置(从前向后查找). 语法:stringObject.indexOf(searc ...
随机推荐
- 我的第一个python web开发框架(24)——系统重构与ORM
小白弄完代码版本管理和接口文档后,兴奋的找到老菜. 小白:老大,我已经按你讲的要求,将代码版本管理和接口文档都搞好了.从项目开始到现在,除了代码编写,感觉学会好多东西啊. 老菜:嗯嗯,实战确实需要掌握 ...
- spring boot +mybatis(通过properties配置) 集成
注:日常学习记录贴,下面描述的有误解的话请指出,大家一同学习. 因为我公司现在用的是postgresql数据库,所以我也用postgresql进行测试 一.前言 1.Spring boot 会默认读取 ...
- centos7下kubernetes(14。kubernetes-DNS访问service)
我们在部署kubernetes时,会自动部署dns组件,其作用是通过dns解析的方法访问service coredns是一个DNS服务器,每当有新的service被创建,kube-dns会添加该ser ...
- 20145203盖泽双《网络对抗技术》拓展:注入:shellcode及return-into-libc攻击
20145203盖泽双<网络对抗技术>拓展:注入:shellcode及return-into-libc攻击 一.注入:shellcode 1.编写一段用于获取Shellcode的C语言代码 ...
- C++ cmake
cmake_minimum_required(VERSION 2.8) project(helloworld) option add_exectuable 告诉工程生成一个可执行文件. add_lib ...
- python之zip打包
import zipfile # 压缩 z = zipfile.ZipFile('z.zip', 'w') z.write('xo.xml') z.write('xxxoo.xml') z.close ...
- C++笔记-并发编程 异步任务(async)
转自 https://www.cnblogs.com/diysoul/p/5937075.html 参考:https://zh.cppreference.com/w/cpp/thread/lock_g ...
- Golang 入门系列(八) cron定时任务
1.cron 表达式的基本格式 Go 实现的cron 表达式的基本语法跟linux 中的 crontab基本是类似的.cron(计划任务),就是按照约定的时间,定时的执行特定的任务(job).cro ...
- 「学习笔记」min_25筛
前置姿势 魔力筛 其实不看也没关系 用途和限制 在\(\mathrm{O}(\frac{n^{0.75}}{\log n})\)的时间内求出一个积性函数的前缀和. 所求的函数\(\mathbf f(x ...
- vue 图片懒加载 vue-lazyload
图片懒加载 在实际的项目开发中,我们通常会遇见这样的场景:一个页面有很多图片,而首屏出现的图片大概就一两张,那么我们还要一次性把所有图片都加载出来吗?显然这是愚蠢的,不仅影响页面渲染速度,还浪费带宽. ...