Search code examples
c#.netcountingalphanumeric

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


I want to only count alphanumerics in a string array - no spaces, punctuation, etc.

I have this clunky code:

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;
}

What is a better/more efficient way of only counting alphanumerics?


Solution

  • Use char.IsLetterOrDigit method to get only alphanumerics, Count from System.Linq to count them and finally Sum to get a total count.

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