开发者

C# Linq non-vowels

开发者 https://www.devze.com 2022-12-12 11:48 出处:网络
From the given string (i.e) string str = \"dry sky one two try\"; v开发者_如何学编程ar nonVowels = str.Split(\' \').Where(x => !x.Contains(\"aeiou\")); (not working).

From the given string

(i.e)

string str = "dry sky one two try";
v开发者_如何学编程ar nonVowels = str.Split(' ').Where(x => !x.Contains("aeiou")); (not working).

How can i extract non-vowel words?


Come on now y'all. IndexOfAny is where it's at. :)

// if this is public, it's vulnerable to people setting individual elements.
private static readonly char[] Vowels = "aeiou".ToCharArray();

// C# 3
var nonVowelWorks = str.Split(' ').Where(word => word.IndexOfAny(Vowels) < 0);

// C# 2
List<string> words = new List<string>(str.Split(' '));
words.RemoveAll(delegate(string word) { return word.IndexOfAny(Vowels) >= 0; });


This should work:

var nonVowels = str.Split(' ').Where(x => x.Intersect("aeiou").Count() == 0);

String.Contains requires you to pass a single char. Using Enumerable.Contains would only work for a single char, as well - so you'd need multiple calls. Intersect should handle this case.


Something like:

var nonVowelWords = str.Split(' ').Where(x => Regex.Match(x, @"[aeiou]") == null);


string str = "dry sky one two try";
var nonVowels = str.ToCharArray()
    .Where(x => !new [] {'a', 'e', 'i', 'o', 'u'}.Contains(x));
0

精彩评论

暂无评论...
验证码 换一张
取 消