在 C# 字符串中引用字母字符

Referencing Alphabetic characters in C# string

我有一个字符串,我试图在其中删除所有非字母字符。在下面的 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);
    }
}

这样写看起来很草率,而且很费时间。 有什么建议么?谢谢

试试这个

var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());

这将为您提供变量 alphaPhrase,其中包含 phrase

中的所有字母

我刚刚尝试测量 LINQ 和 Regex(设置 RegexOptions.Compiled)方法的性能。事实证明 Regex 更有效 但只有你第一次 运行 代码 :

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();

输出(运行 2 通过停止代码执行并将箭头向上拖动到 stopwatch 声明行来执行):

stopwatch.Elapsed.TotalSeconds      = 0.0117504 / (Run 2) 0.0000247
stopwatchRegex.Elapsed.TotalSeconds = 0.0026807 / (Run 2) 0.0012448