我正在使用正则表达式来匹配模式,例如在以下示例中我正在匹配字符串以计算元音。
void VowelsCountInEachWord()
{
Regex rx = new Regex("[aeiou]");
var words=new string[]
{"aesthetic", "benevolent", "abstract",
"capricious", "complacent", "conciliatory",
"devious", "diligent", "discernible","dogmatic",
"eccentric","fallacious","indifferent","inquisitive",
"meticulous","pertinent","plausible", "reticent"
};
var filter = from w in words where (rx.IsMatch(w.ToLower())) select new
{w,count=VowelsCounting(w)};
foreach (var v in filter)
{
Console.WriteLine("String {0} contains {1} vowels", v.w, v.count);
}
}
public int VowelsCounting(string value)
{
int cnt=0;
foreach (char c in value)
{
switch (c)
{
case 'a':cnt++;break;
case 'e':cnt++;break;
case 'i':cnt++;break;
case 'o':cnt++;break;
case 'u':cnt++;break;
}
}
return cnt++;
}
1) 在不使用正则表达式的情况下,C# 是否提供任何匹配模式的构造?
2)为了对字符串计数单个字符,我需要派生自己的方法吗?