仅计算字符串数组中的字母数字字符的更有效方法是什么?

What is a more efficient way to only count alphanumeric characters in an array of String?

我只想计算字符串数组中的字母数字 - 没有空格、标点符号等

我有这个笨拙的代码:

private int GetCountOfCharsInDoc(string[] _lines)
{
    int iCountOfChars = 0;
    string sLine;
    foreach (string line in _lines)
    {
        sLine = line.Replace(" ", string.Empty);
        sLine = line.Replace(".", string.Empty);
        sLine = line.Replace("?", string.Empty);
        sLine = line.Replace(",", string.Empty);
        sLine = line.Replace(";", string.Empty);
        sLine = line.Replace(":", string.Empty);
        sLine = line.Replace("(", string.Empty);
        sLine = line.Replace(")", string.Empty);
        sLine = line.Replace("'", string.Empty);
        sLine = line.Replace("\"", string.Empty);
        iCountOfChars = iCountOfChars + sLine.Count();
    }
    return iCountOfChars;
}

什么是 better/more 只计算字母数字的有效方法?

尝试使用 Char.IsLetterChar.IsDigit:

_lines.Sum(s => s.Count(c => Char.IsLetter(c) || Char.IsDigit(c)))

或者只是:

_lines.Sum(s => s.Count(c => Char.IsLetterOrDigit(c)))

使用 char.IsLetterOrDigit method to get only alphanumerics, Count from System.Linq to count them and finally Sum 获得总计数。

private int GetCountOfCharsInDoc(string[] _lines)
{
    return _lines.Sum(line => line.Count(char.IsLetterOrDigit));
}

或者如果您不想使用 Linq,您可以遍历每个字符并使用 char.IsLetterOrDigit():

进行检查
int n = 0;
foreach (string line in _lines) {
    foreach (char c in line) {
        if (char.IsLetterOrDigit(c)) n++;
    }
}
return n;

您可以简单地使用正则表达式从您的文本中仅提取字母数字,然后计算它。

代码如下:

 var text = "your string";
 var count = Regex.Replace(text , @"[^a-zA-Z0-9]", "").Count();