patterncsharpMinor
Count words that are longer than a set Length
Viewed 0 times
arelongerwordsthanlengththatcountset
Problem
This is working, but I want to know if is this a place where
Test class gives it the input like
Lion, Ape, Tiger, Zebra and 4
So it would return 2 since there are two words with more than 4 letters
IEnumerable can be used?public static int LongerThanStingCompair(string s, int n)
{
int counter = 0;
// splits based on nextLine break
var sCount = s.Split('\n');
// Cast to list
sCount.ToList();
foreach (var item in sCount)
{
//checks to see if words are a certain charLength
if (item.Length > n)
{
counter++;
}
}
return counter;
}Test class gives it the input like
Lion, Ape, Tiger, Zebra and 4
So it would return 2 since there are two words with more than 4 letters
Solution
Signature:
Compair is misspelled, as is Sting - they should be Compare and String, respectively. Although, a better name might be
On to your code:
The comment is unnecessary and slightly wrong. The code splits on all new line characters.
This comment is also incorrect - that doesn't simply cast it creates a new list from an array. It's unnecessary because you only need to enumerate the lines - you don't need the functionality of the list.
Here's a Linq based alternate for you:
public static int LongerThanStingCompair(string s, int n)Compair is misspelled, as is Sting - they should be Compare and String, respectively. Although, a better name might be
CountLinesLongerThan.s and n aren't great names for parameters.On to your code:
// splits based on nextLine break
var sCount = s.Split('\n');The comment is unnecessary and slightly wrong. The code splits on all new line characters.
// Cast to list
sCount.ToList();This comment is also incorrect - that doesn't simply cast it creates a new list from an array. It's unnecessary because you only need to enumerate the lines - you don't need the functionality of the list.
Here's a Linq based alternate for you:
public static int CountLinesLongerThan(string source, int characterLimit)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return source.Split('\n')
.Count(line => line.Length > characterLimit);
}Code Snippets
public static int LongerThanStingCompair(string s, int n)// splits based on nextLine break
var sCount = s.Split('\n');// Cast to list
sCount.ToList();public static int CountLinesLongerThan(string source, int characterLimit)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return source.Split('\n')
.Count(line => line.Length > characterLimit);
}Context
StackExchange Code Review Q#104235, answer score: 6
Revisions (0)
No revisions yet.