我有一个字符串,我试图删除任何非字母字符。在下面的foreach循环中,我想知道是否有更好的方法来引用字母字符而不必输入每个字符而不使用正则表达式方法。
foreach(char c in phrase) {
if (!(c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f' || c == 'g' || c == 'h' || c == 'i' ||
c == 'j' || c == 'k' || c == 'l' || c == 'm' || c == 'n' || c == 'o' || c == 'p' || c == 'q' || c == 'r' || c == 's' ||
c == 't' || c == 'u' || c == 'v' || c == 'w' || c == 'x' || c == 'y' || c == 'z')) {
int i = phrase.IndexOf(c);
phrase = phrase.Remove(i, 1);
}
}
以这种方式写出来似乎很草率,这可能很费时间。 有什么建议?感谢
答案 0 :(得分:2)
试试这个
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
这将为您提供变量alphaPhrase
,其中包含phrase
答案 1 :(得分:1)
我刚尝试测量LINQ和Regex(使用RegexOptions.Compiled
设置)方法的性能。事实证明正则表达式更有效但只是第一次运行代码时:
var nonAlpha = new Regex(@"\P{L}+", RegexOptions.Compiled);
var phrase = "!@#$%^&*()_+=-0987654321`~qwerty{}|[]\';:\"/.,<>?";
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
stopwatch.Stop();
var stopwatchRegex = new System.Diagnostics.Stopwatch();
stopwatchRegex.Start();
var alphaPhrase2 = nonAlpha.Replace(phrase, string.Empty);
stopwatchRegex.Stop();
输出(通过暂停代码执行并将箭头向上拖动到stopwatch
声明行来执行运行2):
stopwatch.Elapsed.TotalSeconds = 0.0117504 / (Run 2) 0.0000247
stopwatchRegex.Elapsed.TotalSeconds = 0.0026807 / (Run 2) 0.0012448