内容简介:翻译自:https://stackoverflow.com/questions/5590890/c-how-to-get-the-length-of-string-in-string
我在C#中有一个字符串集合.我的代码看起来像这样:
string[] lines = System.IO.File.ReadAllLines(@"d:\SampleFile.txt");
我想要做的是找到该集合中字符串的最大长度并将其存储在变量中.目前,我手动编码,像?
int nMaxLengthOfString = 0;
for (int i = 0; i < lines.Length;i++ )
{
if (lines[i].Length>nMaxLengthOfString)
{
nMaxLengthOfString = lines[i].Length;
}
}
上面的代码为我工作,但我正在寻找一些内置的功能,以保持效率,因为在myfile中将有数千行:(
LINQ更简单的方法是:
int maxLength = lines.Max(x => x.Length);
请注意,如果您使用的是.NET 4,则不需要先将所有行读入数组,如果以后不需要它们:
// Note call to ReadLines rather than ReadAllLines. int maxLength = File.ReadLines(filename).Max(x => x.Length);
(如果您不使用.NET 4,则可以轻松编写File.ReadLines的等效文件.)
这在内存方面会更有效,但从根本上说你必须从磁盘读取每一行,你需要迭代这些行来找到最大长度.磁盘访问可能是当然的瓶颈.
翻译自:https://stackoverflow.com/questions/5590890/c-how-to-get-the-length-of-string-in-string
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Django 1.0 Template Development
Scott Newman / Packt / 2008 / 24.99
Django is a high-level Python web application framework designed to support the rapid development of dynamic websites, web applications, and web services. Getting the most out of its template system a......一起来看看 《Django 1.0 Template Development》 这本书的介绍吧!
URL 编码/解码
URL 编码/解码
html转js在线工具
html转js在线工具