C# VII: 统计文本行数
2024-10-06 23:26:40
本文基于StackOverflow的以下问题收集整理而成。
What is the fastest waty to count newlines in a large .NET string: http://stackoverflow.com/questions/2557002/what-is-the-fastest-way-to-count-newlines-in-a-large-net-string
How to count lines in a string: http://stackoverflow.com/questions/11189331/how-to-count-lines-in-a-string
方法一
private static int Count1(string s)
{
int len = s.Length;
int c = 0;
for (int i=0; i < len; i++)
{
if (s[i] == '\n') c++;
}
return c+1;
}
方法二
private static int Count2(string s)
{
int count = -1;
int index = -1;
do
{
count++;
index = s.IndexOf('\n', index + 1);
}
while (index != -1);
return count+1;
}
方法三
private static int Count3(string s)
{
return s.Count( c => c == '\n' ) + 1;
}
方法四
private static int Count4(string s)
{
int n = 0;
foreach( var c in s )
{
if ( c == '\n' ) n++;
}
return n+1;
}
方法五
private static int Count5(string s)
{
var a = s.ToCharArray();
int c = 0;
for (int i=0; i < a.Length; i++)
{
if (a[i]=='\n') c++;
}
return c+1;
}
性能测试结果显示,最快到最慢为:方法四,方法二,方法一,方法五和方法二。方法二不仅最慢,而且差了1个数量级。
方法六
int numLines = aDiff.text.Length - aDiff.text.Replace(Environment.NewLine, string.Empty).Length;
方法七
int numLines = aDiff.text.Split('\n').Length;
是为之记。
Alva Chien
2016.9.5
最新文章
- [No00008B]远程桌面发送“Ctrl+Alt+Delete”组合键调用任务管理器
- Redis 配置文件
- 推荐几个好用的在线svn空间
- webstorm调试Node的时候配置
- 如何启用Service,如何停用Service
- wxPython学习笔记(初识)
- canvas在手机qq浏览器显示错乱
- PHP设计模式之委托模式
- 负载均衡软件LVS分析四(测试)
- OC中成员属性 成员变量
- 漫谈android系统(4)bring up panel
- 在Windows Server 2008 R2下搭建jsp环境(四)-在测试的过程中可能出现的问题
- 制作docker-jdk7-zookeeper镜像(非集群版)
- SaltStack 安装、简单配置和远程执行
- Java设计模式之十一 ---- 策略模式和模板方法模式
- Luogu4622 COCI2012-2013#6 JEDAN 组合、DP
- 对spring cloud config的一点理解
- 转:cookie.setPath()用法
- Spring MVC和Spring Data JPA之按条件查询和分页(kkpaper分页组件)
- QQ消息无限发送!源代码