【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 ...
随机推荐
- SQLServer之创建分布式事务
分布式事务创建注意事项 指定一个由 Transact-SQL 分布式事务处理协调器 (MS DTC) 管理的 Microsoft 分布式事务的起点. 执行 BEGIN DISTRIBUTED TRAN ...
- Hive的命名空间
Hive的命名空间分为:hiveconf , system, env 和 hivevar 1.hiveconf 的命名空间指的是hive-site.xml下面配置的环境变量 2.system的命名空间 ...
- django 创建admin用户名跟密码
一.django中创建用户名和密码 (venv) D:\project\py37project\Djangopro\Procrm>Python37 manage.py createsuperus ...
- 初步了解.net
一..net和C#是什么关系 .net是一个程序运行的平台,它是c#,vb,F#等程序运行的平台,为这些语言提供基础类库.公共语言运行时(CLR)等相关支持. C#是支持.net的一种编程语言..ne ...
- HBase 是列式存储数据库吗
在介绍 HBase 是不是列式存储数据库之前,我们先来了解一下什么是行式数据库和列式数据库. 行式数据库和列式数据库 在维基百科里面,对行式数据库和列式数据库的定义为:列式数据库是以列相关存储架构进行 ...
- 19 python初学(os 模块,sys 模块,hashlib 模块)
os 模块: # _author: lily # _date: 2019/1/13 import os print(os.getcwd()) # 得到当前的工作目录 # print(os.chdir( ...
- Eclipse中的快捷键
Ctrl+1:快捷修复(数字 1 不是字母 l) 将鼠标悬停到出错区域,按 Ctrl+1,出现快捷修复的菜单, 按上下方向键选择一种修复方式即可. 也可以将光标移动到出错区域,按 F2 + Enter ...
- JavaWeb工程中web.xml基本配置(转载学习)
一.理论准备 先说下我记得xml规则,必须有且只有一个根节点,大小写敏感,标签不嵌套,必须配对. web.xml是不是必须的呢?不是的,只要你不用到里面的配置信息就好了,不过在大型web工程下使用该文 ...
- Lepus搭建企业级数据库慢查询分析平台
前言 Lepus的慢查询分析平台是独立于监控系统的模块,该功能需要使用percona-toolkit工具来采集和记录慢查询日志,并且需要部署一个我们提供的shell脚本来进行数据采集.该脚本会自动开启 ...
- css3学习系列之移动
transform功能 放缩 使用sacle方法实现文字或图像的放缩处理,在参数中指定缩放倍率,比如sacle(0.5)表示缩小50%,例子如下: <!DOCTYPE html> < ...