In: Computer Science
Write a method in C# which takes string as an argument and extracts all words of length between 4 to 5 and contains vowels in it. Method returns an array of type string containing words which satisfied above criteria. Show these words in main().
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
string sentence = "Welcome to array world shy fly crypt";
List<string> extractedWords = extract(sentence);
Console.WriteLine("[{0}]", string.Join(", ", extractedWords));
}
public static List<string> extract(string sentence){
// splitting each word
string[] words = sentence.Split(' ');
// we dont know how many elements satisfy the condition so
// we are using List Collection
List<string> newList = new List<string>();
for(int i=0;i<words.Length;i++){
string word = words[i];
// checking length
bool lengthFlag = word.Length == 4 || word.Length == 5;
// checking is vowel or not
bool vowelFlag = word.Contains("a")||word.Contains("A")||
word.Contains("e")||word.Contains("E")||
word.Contains("i")||word.Contains("I")||
word.Contains("o")||word.Contains("O")||
word.Contains("u")||word.Contains("U");
if( lengthFlag && vowelFlag ){
newList.Add(words[i]);
}
}
return newList;
}
}
Code
Output