Select words with vowels in List<T>

不想你离开。 提交于 2019-12-13 02:33:14

问题


I use StreamReader Class to read from txt file and load it into List, now i want to select on words with vowels and store them into new List so i can use StreamWriter to write only selected words into new txt file


回答1:


To select words from a given list of words (that you retrieve however) you can select the ones that only contain vowels using Linq:

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

If you just want words that contain at least a vowel (its not quite clear from the question):

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

Edit in response to comment:

To select words that have more than one vowel:

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



回答2:


Here is an example that will work. I wrote it in Notepad++, so there could be some ; or similar missing. You can adapt it to your needs:

//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);
    }
}



回答3:


You can do it pretty quickly with Linq and Regex

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

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



回答4:


You can match some regex as well, since you might want to consider y's a vowel. Start with ([aeiou])|([A-Za-z]y), then move on from there if you need something more complex. http://www.nregex.com/nregex/default.aspx is a good place to start if you want to test out your regex.

// 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)"));


来源:https://stackoverflow.com/questions/5862648/select-words-with-vowels-in-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!