Ok, so I know that questions LIKE this have been asked a lot on here, but I can\'t seem to make solutions work. I am trying to take a string from a file and find the longest
If you care about performance you don't want to split the string. The reason in order to do the split method will have to traverse the entire string, create new strings for the items it finds to split and put them into an array, computational cost of more than N
, then doing an order by you do another (at least) O(nLog(n))
steps.
You can use a Regex for this, which will be more efficient, because it will only iterate over the string once
var regex = new Regex(@"(\w+)\s",RegexOptions.Compiled);
var match = regex.Match(fileText);
var currentLargestString = "";
while(match.Success)
{
if(match.Groups[1].Value.Length>currentLargestString.Length)
{
currentLargestString = match.Groups[1].Value;
}
match = match.NextMatch();
}
The nice thing about this is that you don't need to break the string up all at once to do the analysis and if you need to load the file incrementally is a fairly easy change to just persist the word in an object and call it against multiple strings
You don't need to do an order by your just looking for the largest item, computational complexity of order by is in most cases O(nLog(n))
, iterating over the list has a complexity of O(n)
var largest = "";
foreach(var item in strArr)
{
if(item.Length>largest.Length)
largest = item;
}