I wrote a program to count words in a sentence that have x number of matching characters. The input string is a multi line string and I need to consider only alternate lines based on given criteria. Also in those filtered lines, I need to further select alternate words and then check if those filtered words match the characters for intersection.
E.g. let's say I have a input string as below and need to find words with 2 or more vowels in them:
string myString = "1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";
now let's say I need to count every 3rd word in every 2nd line and count if these filtered words have 2 or more vowels in it. If this condition is matched, return the matching word count and total line count containing these matching words.
E.g. with criteria of selecting every 2nd line, filtered lines will be {2, 4, 6}. Similarly every 3rd word in these filtered line will be line 2: {"the", "Wars"}, for line 4: {"of", "before"} and for line 6: {"be", "after"}.
For these filtered words, matching words with 2 or more vowels will be {"before"} in line number 4 and word {"after"} in line 6. So the final output will be wordCount = 2 and since these words are from line 4 and 6 so total lineCount = 2.
I wrote the below code using nested for loops that produces the desired output.
public static void Main(string[] args)
{
int vowelCount = 2; // match words with 2 or more vowels
int skipWord = 3; // Consider every 3rd word only
int skipLine = 2; // Consider every 2nd line only
int wordCount = 0;
int lineCount = 0;
string myString = @"1.In order to get a Disneyland ticket
2.that includes the new Star Wars land
3.you must stay at a Disney hotel
4.the night of or night before your visit.
5.Day passes without a hotel
6.reservation will be available after June 23";";
List<string> myList = myString.Split(Environment.NewLine).ToList();
List<string> lineWords = new List<string>();
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (int i = skipLine; i <= myList.Count; i += skipLine)
{
int origWordCount = wordCount;
lineWords = myList[i - 1].Split(' ').ToList();
for (int j = skipWord; j <= lineWords.Count; j += skipWord)
{
char[] wordArr = lineWords[j-1].ToLower().ToCharArray();
int match = vowels.Intersect(wordArr).Count();
if (match >= vowelCount)
wordCount++;
}
if (wordCount > origWordCount)
lineCount++;
}
Console.WriteLine("WordCount : {0}, LineCount : {1}", wordCount, lineCount);
Above code works great but wondering if there is a way to do it without nested loops. I read about linq and lambda expressions but not sure how to use them here.
All comments are appreciated.