简体   繁体   English

C#:如何获取string []中字符串的长度

[英]C#: how to get the length of string in string[]

I have a collection of string in C#. 我在C#中有一个字符串集合。 My Code looks like this: 我的代码如下所示:

string[] lines = System.IO.File.ReadAllLines(@"d:\SampleFile.txt");

What i want to do is to find the max length of string in that collection and store it in variable. 我想做的是在该集合中找到字符串的最大长度,并将其存储在变量中。 Currently, i code this manually, like? 目前,我手动编写此代码,例如?

int nMaxLengthOfString = 0;
for (int i = 0; i < lines.Length;i++ )
{               
   if (lines[i].Length>nMaxLengthOfString)
   {
      nMaxLengthOfString = lines[i].Length;
   }
}

The code above does the work for me, but i am looking for some built in function in order to maintain efficiency, because there will thousand of line in myfile :( 上面的代码为我完成了工作,但是我正在寻找一些内置函数来保持效率,因为myfile中将有数千行:(

A simpler way with LINQ would be: 使用LINQ的更简单方法是:

int maxLength = lines.Max(x => x.Length);

Note that if you're using .NET 4, you don't need to read all the lines into an array first, if you don't need them later: 请注意,如果您使用的是.NET 4,则无需先将所有行读入数组,如果稍后不再需要它们:

// Note call to ReadLines rather than ReadAllLines.
int maxLength = File.ReadLines(filename).Max(x => x.Length);

(If you're not using .NET 4, it's easy to write the equivalent of File.ReadLines .) (如果您不使用.NET 4,则很容易编写等效于File.ReadLines 。)

That will be more efficient in terms of memory, but fundamentally you will have to read every line from disk, and you will need to iterate over those lines to find the maximum length. 这将是在内存方面更有效,但根本上,你不得不从磁盘中读取每一行,你需要遍历这些行找到的最大长度。 The disk access is likely to be the bottleneck of course. 当然,磁盘访问可能是瓶颈。

The efficiency will certainly not be worse in your case, if not better. 如果不是更好,效率当然不会变差

But if you're looking to be succinct , try lambdas with LINQ: 但是,如果您希望简洁 ,请尝试使用LINQ的lambda:

lines.Aggregate((a, b) => Math.Max(a.Length, b.Length));

Btw, minor point: you can technically stop reading if the amount of data left is less than the longest line you've found. 顺便说一句,次要点:从技术上讲,如果剩余数据量小于找到的最长行,则可以停止读取。 So you can technically save some steps, although it's probably not worth the code. 因此,尽管可能不值得编写代码,但从技术上讲,您可以节省一些步骤。


Completely irrelevant, but just because I feel like it, here's the (elegant!) Scheme version: 完全无关紧要,但是只是因为我觉得这样,所以这是(优雅的!)Scheme版本:

(reduce max (map length lines))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM