在List <t> </t>中选择带元音的单词

时间:2011-05-02 21:25:03

标签: c# pattern-matching

我使用StreamReader Class从txt文件读取并将其加载到List中,现在我想选择带有元音的单词并将它们存储到新的List中,这样我就可以使用StreamWriter将所选单词写入新的txt文件

4 个答案:

答案 0 :(得分:2)

要从给定的单词列表(您检索的单词)中选择单词,您可以使用Linq选择包含元音的单词:

string vowels = "aeiou";
List<string> words = new List<string>();
//words populated
var vowelWords = words.Where( word => word.All( c => vowels.Contains(c) ))
                      .ToList();

如果你只想要包含至少一个元音的单词(问题中不太清楚):

var vowelWords = words.Where( word => word.Any( c => vowels.Contains(c) ))
                      .ToList();

编辑以回应评论:

选择包含多个元音的单词:

var vowelWords = words.Where(word => word.Count(c => vowels.Contains(c)) > 1)
                      .ToList();

答案 1 :(得分:1)

这是一个可行的例子。我在Notepad ++中写了它,因此可能会有一些;或类似的遗漏。您可以根据自己的需要进行调整:

//Reading...
List<string> originalWords = new List<string>();

using (var reader = new StreamReader(...)) {
    while (!reader.EndOfLine()) {
        string line = reader.ReadLine();
        var splitted = line.Split(new string[] {" "}, StringSplitOptions.None);
        foreach (var word in splitted) {
            if (!originalWords.Contains(word)) {
                originalWords.Add(word);
            }
        }
    }
}

//Filtering...
List<string> filtered = new List<string>();
string vowels = "aeiou";

foreach (var word in originalWords) {
    foreach (var vowel in vowels) {
        if (word.Contains(vowel))
            filtered.Add(vowel);
            break;
    }
}

//Writing...
using (var writer = new StreamWriter(...)) {
    foreach (var word in filtered) {
        writer.WriteLine(word);
    }
}

答案 2 :(得分:1)

你可以用Linq和Regex很快地完成它

var words = [your code to get them into a collection]

var withVowels = from word in words
                 where Regex.IsMatch(word, "[AEIOUaeiou]")
                 select word;

答案 3 :(得分:0)

您也可以匹配一些正则表达式,因为您可能想要将y视为元音。从([aeiou])|([A-Za-z]y)开始,如果您需要更复杂的东西,请从那里继续。如果你想测试你的正则表达式,http://www.nregex.com/nregex/default.aspx是一个很好的起点。

// Your words go in here
List<string> words;
// is vowelled a word?
var vowelledWords = words.Where(w => Regex.IsMatch(w, "([aeiou])|([A-Za-z]y)"));