【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 ...
随机推荐
- python3 deque(双向队列)
创建双向队列 import collections d = collections.deque() append(往右边添加一个元素) import collections d = collectio ...
- Netty初体验
package netty_starter; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFut ...
- Python中的一些小技巧
1.Boolean值可以当做一个数值 a = [5,6,7,8,9] print(a[True]) #prints 6 print(a[False]) #prints 5 2.两种方法实现 a = 1 ...
- 多线程——multiprocess
先看个误打误撞的写的代码 import os import time import multiprocessing def func(): print('我是func函数1','现在的father进程 ...
- 通过ip查询自己电脑的共享文件夹
查看电脑所有的共享文件或文件夹的三种方法如下: 方法一. 右键点击网上邻居,点击属性进入网上邻居属性页面. 选中本地连接,在窗口的左下方有详细信息,可以看到内网IP,记住IP地址. 直接在地址栏输入记 ...
- Vue-Router模式、钩子
转:https://www.cnblogs.com/heioray/p/7193841.html 模式 vue-router中的模式选项主要在router实例化的时候进行定义的,如下 const ro ...
- Taro项目遇到的问题
1. https://taro-ui.aotu.io/#/docs/questions 请在Taro项目根目录找到 config/index.js 文件中的h5项,添加如下: h5: { ... es ...
- 迷茫<第二篇:回到老家湖南长沙>
2014年8月初,我买了回老家的火车票,当时没有买到坐票,卧铺贵了买不起,所以我就选择了站票,准备站回老家.我现在还记得我当时买的是T1列火车,北京西站到长沙火车站,全程16个小时.当时我就在火车上站 ...
- Redis详解(四)------ redis的底层数据结构
上一篇博客我们介绍了 redis的五大数据类型详细用法,但是在 Redis 中,这几种数据类型底层是由什么数据结构构造的呢?本篇博客我们就来详细介绍Redis中五大数据类型的底层实现. 1.演示数据类 ...
- 软工+C(2): 分数和checklist
// 上一篇:题目设计.点评和评分 // 下一篇:超链接 教学里,建立清晰明确的评分规则并且一开始就公布,对于教师.助教.学生都是重要的. 公布时机 在课程开始的时候,就需要确定并公布评分机制,随着课 ...